Êíèãà: Advanced PIC Microcontroller Projects in C

3.1.19 Modifying the Flow of Control

3.1.19 Modifying the Flow of Control

Statements are normally executed sequentially from the beginning to the end of a program. We can use control statements to modify this normal sequential flow in a C program. The following control statements are available in mikroC programs:

• Selection statements

• Unconditional modifications of flow

• Iteration statements

Selection Statements

There are two selection statements: if and switch.

if Statement The general format of the if statement is:

if (expression)
 Statement1;
else
 Statement2;

or

if (expression) Statement1; else Statement2;

If the expression evaluates to TRUE, Statement1 is executed, otherwise Statement2 is executed. The else keyword is optional and may be omitted. In the following example, if the value of x is greater than MAX then variable P is incremented by 1, otherwise it is decremented by 1:

if (x > MAX) P++;
else P--;

We can have more than one statement by enclosing the statements within curly brackets. For example:

if (x > MAX) {
 P++;
 Cnt = P;
 Sum = Sum + Cnt;
} else P--;

In this example, if x is greater than MAX then the three statements within the curly brackets are executed, otherwise the statement P-- is executed. Another example using the if statement is:

if (x > 0 && x < 10) {
 Total += Sum;
 Sum++;
} else {
 Total = 0;
 Sum = 0;
}

switch Statement  The switch statement is used when a number of conditions and different operations are performed if a condition is true. The syntax of the switch statement is:

switch (condition) {
case condition1:
 Statements;
break;
case condition2:
 Statements;
 break;
.....................
.....................
case condition:
 Statements;
 break;
default:
 Statements;
}

The switch statement functions as follows: First the condition is evaluated. The condition is then compared to condition1 and if a match is found, statements in that case block are evaluated and control jumps outside the switch statement when the break keyword is encountered. If a match is not found, condition is compared to condition2 and if a match is found, statements in that case block are evaluated and control jumps outside the switch statements, and so on. The default is optional, and statements following default are evaluated if the condition does not match any of the conditions specified after the case keywords.

In the following example, the value of variable Cnt is evaluated. If Cnt = 1, A is set to 1. If Cnt = 10, B is set to 1, and if Cnt = 100, C is set to 1. If Cnt is not equal to 1, 10, or 100 then D is set to 1:

switch (Cnt) {
case 1:
 A = 1;
 break;
case 10:
 B = 1;
 break;
case 100:
 C = 1;
 break;
default:
 D = 1;
}

Because white spaces are ignored in C language we can also write the preceding code as:

switch (Cnt) {
case 1:
 A = 1;
 break;
case 10:
 B = 1;
 break;
case 100:
 C = 1;
 break;
default:
 D = 1;
}

Example 3.1

In an experiment the relationship between X and Y values are found to be:

X Y
1 3.2
2 2.5
3 8.9
4 1.2
5 12.9

Write a switch statement that will return the Y value, given the X value.

Solution 3.1

The required switch statement is:

switch (X) {
case 1:
 Y = 3.2;
 break;
case 2:
 Y = 2.5;
 break;
case 3:
 Y = 8.9;
 break;
case 4:
 Y = 1.2;
 break;
case 5:
 Y = 12.9;
}

Iteration Statements

Iteration statements enable us to perform loops in a program, where part of a code must be repeated a number of times. In mikroC iteration can be performed in four ways. We will look at each one with examples:

• Using for statement

• Using while statement

• Using do statement

• Using goto statement

for Statement  The syntax of a for statement is:

for(initial expression; condition expression; increment expression) {
 Statements;
}

The initial expression sets the starting variable of the loop, and this variable is compared against the condition expression before entry into the loop. Statements inside the loop are executed repeatedly, and after each iteration the value of the increment expression is incremented. The iteration continues until the condition expression becomes false. An endless loop is formed if the condition expression is always true.

The following example shows how a loop can be set up to execute 10 times. In this example, variable i starts from 0 and increments by 1 at the end of each iteration. The loop terminates when i=10, in which case the condition i<10 becomes false. On exit from the loop, the value of i is 10:

for(i = 0; i < 10; i++) {
 statements;
}

This loop could also be started by an initial expression with a nonzero value. Here, i starts with 1 and the loop terminates when i = 11. Thus, on exit from the loop, the value of i is 11:

for(i = 1; i <= 10; i++) {
 Statements;
}

The parameters of a for loop are all optional and can be omitted. If the condition expression is left out, it is assumed to be true. In the following example, an endless loop is formed where the condition expression is always true and the value of i starts with 0 and is incremented after each iteration:

/* Endless loop with incrementing i */
for(i=0; ; i++) {
 Statements;
}

In the following example of an endless loop all the parameters are omitted:

/* Example of endless loop */
for(; ;) {
 Statements;
}

In the following endless loop, i starts with 1 and is not incremented inside the loop:

/* Endless loop with i = 1 */
for(i=1; ;) {
 Statements;
}

If there is only one statement inside the for loop, he curly brackets can be omitted as shown in the following example:

for(k = 0; k < 10; k++)Total  = Total + Sum;

Nested for loops can also be used. In a nested for loop, the inner loop is executed for each iteration of the outer loop. In the following example the inner loop is executed five times and the outer loop is executed ten times. The total iteration count is fifty:

/* Example of nested for loops */
for(i = 0; i < 10; i++) {
 for(j = 0; j < 5; j++) {
  Statements;
 }
}

In the following example, the sum of all the elements of a 3?4 matrix M is calculated and stored in a variable called Sum:

/* Add all elements of a 3x4 matrix */
Sum = 0;
for(i = 0; i < 3; i++) {
 for(j = 0; j < 4; j++) {
  Sum = Sum + M[i][j];
 }
}

Since there is only one statement to be executed, the preceding example could also be written as:

/* Add all elements of a 3x4 matrix */
Sum = 0;
for(i = 0; i < 3; i++) {
 for(j = 0; j < 4; j++) Sum = Sum + M[i][j];
}

while Statement  The syntax of a while statement is:

while (condition) {
 Statements;
}

Here, the statements are executed repeatedly until the condition becomes false, or the statements are executed repeatedly as long as the condition is true. If the condition is false on entry to the loop, then the loop will not be executed and the program will continue from the end of the while loop. It is important that the condition is changed inside the loop, otherwise an endless loop will be formed.

The following code shows how to set up a loop to execute 10 times, using the while statement:

/* A loop that executes 10 times */
k = 0;
while (k < 10) {
 Statements;
 k++;
}

At the beginning of the code, variable k is 0. Since k is less than 10, the while loop starts. Inside the loop the value of k is incremented by 1 after each iteration. The loop repeats as long as k 10 and is terminated when k = 10. At the end of the loop the value of k is 10.

Notice that an endless loop will be formed if k is not incremented inside the loop:

/* An endless loop */
k = 0;
while (k < 10) {
 Statements;
}

An endless loop can also be formed by setting the condition to be always true:

/* An endless loop */
while (k == k) {
 Statements;
}

Here is an example of calculating the sum of numbers from 1 to 10 and storing the result in a variable called sum:

/* Calculate the sum of numbers from 1 to 10 */
unsigned int k, sum;
k = 1;
sum = 0;
while(k <= 10) {
 sum = sum + k;
 k++;
}

It is possible to have a while statement with no body. Such a statement is useful, for example, if we are waiting for an input port to change its value. An example follows where the program will wait as long as bit 0 of PORTB (PORTB.0) is at logic 0. The program will continue when the port pin changes to logic 1:

while(PORTB.0 == 0); // Wait until PORTB.0 becomes 1

or

while(PORTB.0);

It is also possible to have nested while statements.

do Statement  A do statement is similar to a while statement except that the loop executes until the condition becomes false, or, the loop executes as long as the condition is true. The condition is tested at the end of the loop. The syntax of a do statement is:

do {
 Statements;
} while (condition);

The first iteration is always performed whether the condition is true or false. This is the main difference between a while statement and a do statement. The following code shows how to set up a loop to execute 10 times using the do statement:

/* Execute 10 times */
k = 0;
do {
 Statements;
 k++;
} while (k < 10);

The loop starts with k = 0, and the value of k is incremented inside the loop after each iteration. At the end of the loop k is tested, and if k is not less than 10, the loop terminates. In this example because k = 0 is at the beginning of the loop, the value of k is 10 at the end of the loop.

An endless loop will be formed if the condition is not modified inside the loop, as shown in the following example. Here k is always less than 10:

/* An endless loop */
k = 0;
do {
 Statements;
} while (k < 10);

An endless loop can also be created if the condition is set to be true all the time:

/* An endless loop */
do {
 Statements;
} while (k == k);

It is also possible to have nested do statements.

Unconditional Modifications of Flow

goto Statement  A goto statement can be used to alter the normal flow of control in a program. It causes the program to jump to a specified label. A label can be any alphanumeric character set starting with a letter and terminating with the colon (“:”) character.

Although not recommended, a goto statement can be used together with an if statement to create iterations in a program. The following example shows how to set up a loop to execute 10 times using goto and if statements:

/* Execute 10 times */
k = 0;
Loop:
 Statements;
 k++;
if (k < 10) goto Loop;

The loop starts with label Loop and variable k = 0 at the beginning of the loop. Inside the loop the statements are executed and k is incremented by 1. The value of k is then compared with 10 and the program jumps back to label Loop if k 10. Thus, the loop is executed 10 times until the condition at the end becomes false. At the end of the loop the value of k is 10.

continue and break Statements  continue and break statements can be used inside iterations to modify the flow of control. A continue statement is usually used with an if statement and causes the loop to skip an iteration. An example follows that calculates the sum of numbers from 1 to 10 except number 5:

/* Calculate sum of numbers 1,2,3,4,6,7,8,9,10 */
Sum = 0;
i = 1;
for(i = 1; i <= 10; i++) {
 if (i == 5) continue; // Skip number 5
 Sum = Sum + i;
}

Similarly, a break statement can be used to terminate a loop from inside the loop. In the following example, the sum of numbers from 1 to 5 is calculated even though the loop parameters are set to iterate 10 times:

/* Calculate sum of numbers 1,2,3,4,5 */
Sum = 0;
i = 1;
for(i = 1; i <= 10; i++) {
 if (i > 5) break; // Stop loop if i > 5
 Sum = Sum + i;
}

Îãëàâëåíèå êíèãè


Ãåíåðàöèÿ: 1.290. Çàïðîñîâ Ê ÁÄ/Cache: 3 / 1
ïîäåëèòüñÿ
Ââåðõ Âíèç