Файл: Interfacing with C plus plus-programing communication with microcontrolers (K. Bentley, 2006).pdf
ВУЗ: Не указан
Категория: Не указан
Дисциплина: Не указана
Добавлен: 14.06.2025
Просмотров: 3586
Скачиваний: 1
7 DRIVING LEDS 151
cout << endl;
}
Implementing this code in a program will produce the output shown in Figure 7-2:
*
**
***
****
*****
Figure 7-2 The output of the nested for loop operation.
The body of the outer for loop starts at the open brace and ends at the close brace. Between these two braces is the inner for loop. The inner for loop has no braces because it only has the one statement as its body:
cout << ‘*’;
The second statement of the outer for loop is:
cout << endl;
and will be executed after the inner for loop has completed all its iterations. Each iteration of the inner for loop prints the character ‘*’ on the screen and increments the loop counter j. Printing for that line ceases when the value of j reaches that of the outer loop counter i. Therefore, each iteration of the outer for loop consists of j iterations of the inner for loop.
7.2.2 The while Loop and the do–while Loop
Repetitive iterations as performed with the for loop can be carried out using the while loop. The while loop is similar to the for loop without initialising and incremental expressions. It simply has a test expression enclosed within a pair of parentheses that is evaluated at the start of the loop. This expression must evaluate to true for the body of the while loop to be executed. If it evaluates to false (zero) the loop will be terminated. It is possible that the body of the while loop is not executed at all - if in the first entry of the loop, the test expression evaluates to false or zero.
Because initialising and incremental expressions are omitted, while loops do not generally deploy a loop counter. However, the while loop can be used to implement the behaviour of a for loop and vice-versa. In general, while loops are implemented when the exact number of iterations are not known.
152 7 DRIVING LEDS
Test expression is evaluated first.
while(i < 10000)
{
i++;
}
Statements in the body
do
Statements in the body
{
i++;
}
while(i < 10000)
Test expression is evaluated last.
Figure 7-3 The while and do-while loops.
The do-while statement is very similar to the while statement. The difference being that the test expression is evaluated at the end of the loop resulting in at least one execution of the body of the loop. The statements in the body of the loop are between the keyword do and the keyword while. Braces must be used if the body is a compound statement. Figure 7-3 shows the anatomy of the two types of loop.
7.3 Branching
7.3.1 The if Statement
The if statement has a conditional expression enclosed within a pair of parentheses placed immediately after the keyword if. The most general form of the if statement has a true clause and a false clause separated by the keyword else. The true clause consists of the statements before else and the false clause consists of the statements after else. The conditional expression will evaluate to true or false. If it evaluates to true, the true clause will be executed and the false clause will be ignored, otherwise the false clause will be executed and the true clause will be ignored.
If there are multiple statements in any of the clauses, they must be placed within braces ({ and }) to form compound statements. Within these compound statements there may be other if statements. If this is the case they are known as nested if statements. In nested if statements, the else keyword will bind to the last opened if statement without an else.
7 DRIVING LEDS 153
conditional expression
The keyword if
if(i < 10000)
{
statements
}
The keyword else separates the true
and false clauses else
{
statements
}
The true clause. This section will be executed if the conditional expression evaluates to true. The braces are necessary if there is more than one statement in the true clause.
The false clause. This section will be executed if the conditional expression evaluates to false. The braces are necessary if there is more than one statement in the true clause.
Figure 7-4 The if statement - the most general case.
It is also possible to have if statements with only one clause as shown in Figure 7-5. This clause must be the true clause.
conditional expression
The keyword if
if(i < 10000)
{
statements Statements for the true clause.
}
No else keyword and no false clause. If the conditional expression evaluates to false, no action will be taken.
Figure 7-5 The if statement with only a true clause.
The if statements can be nested as shown in Figure 7-6. In the two examples shown, the else keyword binds to two different if statements. Use of proper indentation helps the programmer to see the correct association for each clause in nested if statements as shown in Figure 7-7.
154 7 DRIVING LEDS
if (<cond. exp. 1>)
{
if (<cond. exp. 2>)
{
<true clause>
}
else
{
<false clause>
}
}
The else binds to the second if statement. The first if statement only has a true clause which contains the second if statement. The second if statement has a true clause and also a false clause.
if (<cond. exp. 1>)
{
if (<cond. exp. 2>)
{
<true clause>
}
}
else
{
<false clause>
}
The else binds to the first if statement. The first if statement has a true clause and a false clause. The second if statement has only a true clause and is within the true clause of the first if statement.
Figure 7-6 Nested if statements without indentation.
if (<cond. exp. 1>) |
if (<cond. exp. 1>) |
|
{ |
{ |
|
if (<cond. exp. 2>) |
if (<cond. exp. 2>) |
|
{ |
{ |
|
<true clause> |
<true clause> |
|
} |
} |
|
else |
} |
|
{ |
else |
|
<false clause> |
{ |
|
} |
<false clause> |
|
} |
} |
|
Figure 7-7 Indented if statements.
7 DRIVING LEDS 155
The use of an if statement is shown in the following fragment of code:
int Number;
cout << “Enter an integer Number “; cin >> Number;
if(Number > 50)
cout << “Number is greater than 50” << endl;
else
cout << “Number is less than or equal to 50” << endl;
The number entered by the user will be tested by the if statement and a message will be printed on the screen displaying the result of the test.
A compact version of the if statement can be implemented using the so-called conditional operator (?:). For example, by checking a variable named Switch, ON/OFF status of the switch can be printed on the screen using:
Switch == 1 ? cout << “on” : cout “off”;
This statement is equivalent to:
if(Switch == 1) cout << “on”;
else
cout << “off”;
7.3.2 The break and continue Statements
The break and continue statements are two important statements that can be used efficiently to enhance the functionality of our programs. Of the two statements, the break statement is more widely used. Their syntax is very simple and always used as follows:
break;
continue;
The break statement is used to terminate the execution of a loop (such as while, do-while, or for) or a switch statement. The continue statement is used to skip and continue the execution of loops. Figure 7-8 shows the two cases.
As mentioned previously, iterative loops can be nested; i.e. one loop within another. Similarly, a switch statement can be placed within a loop. In such situations, the break statement will be associated with the nearest loop or switch statement. The continue statement will be associated with the nearest loop and cannot be used with the switch statement.
The C++ language also supports the use of goto to jump to a label. Use of goto can severely damage the structure of a program. Its use is discouraged and is not explained in this text - see references listed in Section 7.11.
156 7 DRIVING LEDS
int i = 0, Sum = int n = 50;
Always true
while(1)
{
i++;
Sum += i; if(i==n) break;
}
0;
Infinite while loop
When i is equal to n, the if statement will execute break, terminating the infinite while loop.
int Sum = 0;
int n = 20, m = 30;
for(i=0; i<100; i++)
{
if((i>=n) && (i<=m)) continue;
Sum += i;
}
For all values of i between n and m, continue will be executed, forcing all remaining statements within the body of the for loop to be skipped. The next statement to be executed is the incremental expression i++.
Figure 7-8 The break and continue statements.
7.3.3 The switch – case Statement
A switch-case statement is used to select and then execute one of several cases. Selection is carried out by a switch expression located after the keyword switch and enclosed between parenthesis.
The switch expression must produce an integer result.
switch(switch expression)
The body of the switch { statement starts here.
These two must be constant integer expressions such as 3, or 0x0C, etc.
The body of the switch } statement ends here.
case n1 : statements break;
case n2 : statements break;
.
.
.
default : statements
If the switch expression evaluates to n1, these statements will be executed.
If the switch expression evaluates to n2, these statements will be executed.
If the switch expression evaluates to none of the cases listed, the default case will be executed. The default case may be omitted.
Figure 7-9 The switch statement.
7 DRIVING LEDS 157
The switch expression must be of integral type such as char, unsigned char, int, unsigned int, etc. Program control will be transferred to a case statement that matches the value of the switch expression.
The cases are listed within the body of the switch statement. Immediately after the keyword case, there must be a constant integer expression, which must have a unique value. Each case may have any statement including an empty statement. All statements under a case will be executed sequentially.
The break statement must be used to exit a switch statement at the end of a particular case. If break is not used, program execution will flow on to the next case. Optionally, a special case named default may be used to take necessary action if no matching case is found.
Constant Integer Expression
A constant integer expression must produce an integer result and cannot contain
any variables.
#define TWIN 2
Here the symbolic constant TWIN is defined to be a substitute for the number 2.
Then |
TWIN+1 is a constant integer expression. Note that TWIN is not a |
|||
variable. |
||||
However, if |
int a=0; |
|||
Then |
a+1 |
is not a constant integer expression, because a is a variable. |
||
7.4 Arrays
An array is a collection of objects of the same type. The objects could be fundamental data types or user-defined data types. Each individual object of the collection is referred to as an element. Towards the end of the chapter, we will be using arrays to store LED lighting patterns for the program.
Arrays can be represented in different configurations or number of dimensions as shown in Figure 7-10. Each cell can store one object of the designated type. There is practically no limit to the number of dimensions an array can have.
The size of the array is given by the number of elements (cells) for each dimension. Using Figure 7-10 as an example, the sizes of the arrays are:
1-dimensional array: 5 elements.
2-dimensional array: 3 rows, 5 elements/row. Size = 15 elements.
3-dimensional array: 3 rows, 4 elements/row, 2 elements/row. Size = 24 elements.
158 7 DRIVING LEDS
1 |
||||||||||||||||
0 |
1 |
2 |
3 |
4 |
0 |
1 |
2 |
3 |
4 |
0 |
||||||
0 |
0 |
0 |
1 |
2 |
3 |
|||||||||||
1 Dimensional |
1 |
1 |
||
Array |
2 |
2 |
||
2 Dimensional |
3 Dimensional |
|||
Array |
Array |
Figure 7-10 Diagramatic representation of arrays.
Although the arrays can be represented as shown in Figure 7-10, in your computers memory the elements of the array are stored sequentially row after row, termed row-major fashion. In storing a 3-D array, the first layer is stored first in a rowmajor fashion and then the second layer in row-major fashion and so on.
One-Dimensional Arrays
When declaring one-dimensional arrays, the size of the array is specified within a pair of square brackets immediately after the array identifier. The array subscripts always start with 0 and range to the array size minus one. An example of a declaration is:
int a[10];
This declares an array of 10 int type objects. They are stored in adjacent memory locations starting from the element a[0] ranging up to a[9], making available a set of 10 elements as shown in Figure 7-11. Note that there is no element named a[10]. Attempting to access such an element will be illegal, since this memory location is not part of the array a.
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
Figure 7-11 Schematic of a one-dimensional array.
If a variable subscript is used to access array elements, as in a[i], then i must be an integer expression and as just mentioned must not evaluate to a value outside the permitted range of array subscript values, in this case 0 to 9.
The array elements can be initialised individually during program execution by assigning each element a value. For example, the following code fragment sets the value of all elements to zero: