Computer Programming in CLecture 10

Lecture 10 Repetition - 'for' loops

1Initialisation and Updating

The control of a loop is usually done by checking the value of one or more variables. The variable(s) must contain proper value before being checked, so it must be initialised before the first condition check. Initialisation is the preparation before the execution of the loop.










In the loop, the variable(s) must be changed in order the reach the stopping condition. Otherwise it will be an infinite loop which never stops! Usually we execute the loop a number of times, or until certain value is achieved, which will be the checking done in the loop condition. The changes are known as loop update, usually done as the last action in the loop. Refer to previous examples in the while loop to see the initialisation and updating tasks.










2The forLoop

A more comprehensive type of loop in C is theforloop, which has the following format

for (initialisation expression; loop repetition condition;update expression)

statement;

The repetition is usually controlled by a loop control variable. The for loop is more suitable for counter-controlled loops rather than sentinel-controlled loops, where the number of times the loop is executed can be determined by the programmer.

This variable is initialised and after every repetition of the statement (or compound statement) the variable is updated. After updating the condition is checked to see if it is still true. If it is there is a further repetition of the statement otherwise control passes to the statement following the 'for' block.

Example 1:

for (count = 0;count < 10; count = count + 1)

printf("The value of count is %d ",count);

Above is the example of counter-controlled loop and the loop control variable is count. The count variable is initialised to 0. The printf statement is executed and then count is updated (to 0 + 1). The condition (count < 10) is true so the printf statement is repeated. This continues until count is not < 10. (Note: In this example the loop control variable is used in the statement to be executed.)

Example 2: To sum 5 integers

#include <stdio.h>

int main(void)

{

int number,/* the integer input*/

sum,/* the accumulative sum */

count;/* Loop counter */

sum = 0;/* Initialising the sum */

for (count = 0; count <5;count = count + 1)

/* Looping 5 times */

{printf("Input an integer>"); /* Prompt for input */

scanf("%d",&number);/* Integer input */

sum = sum + number;/*Accumulating the sum */

}

printf("The sum of the 5 integers is %d",sum); /* Output */

return(0);

}

Note: The Loop Control Variable Is Not Used In the Executed Statements

Example 3: To evaluate the factorial value of a given number.

/* Input routine*/

printf("Input an integer>");

scanf("$d",&num);

/* Calculate n factoial*/

product = 1;

for ( i = num; i > 1; i = i - 1);

product = product * i;

/* Output the result*/

printf("The factorial value is %d",product);

3The nested for Loop

Loops may be nested just like other control structures. Nested loops consist of an outer loop with one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, their loop control expressions are reevaluated, and all required iterations are performed.

Example 1:

printf(“IJ\n“);

for (i = 1; i < 4; ++i)/* heading of outer for loop */

{

printf(“Outer %6d\n“, i);

for (j = 0; j < i; ++j) /* heading of inner for loop */

{

printf(“ Inner %9d\n“, i);

} /* end of inner for loop */

} /* end of outer for loop */

4forLoop Variants

We can include multiple expressions in any field of the for loop provided we separate the expressions by commas:

for (i = 0, j = 10; i <10; i++, j--)

.....

Just as the need may arise to include more than one expression in a field, we can also omit one or more fields from the for statement:

for (; j!=100; j++)

.....

for (k=10; k >=0; )

.....

for (;;)

.....

5The break and continue Statements in Loop Structure

The break statement interrupts the execution of a loop and causes an exit to the statement that follows the loop.

The continue statement stops the current iteration of a loop and causes the next iteration of the loop to begin immediately, beginning with the evaluation of the loop condition. The statement may only occur inside for, while, and do-while loops.

Example 1:

while(num <= 10)

{

scanf(“%lf“, &x);

if (x < 0.0)

break;/* exit loop if x is negative */

printf(“%f\n“, sqrt(x));

}

/* break jumps to here */

Example 2: The following example is a calculator program that allows us to enter an arithmetic expression. The program will compute the value of the expression and print it in a loop for as long as the user wants to continue.

do

{

printf("Type an arithmetic expression as ");

printf("<constant> <operator> <constant>");

printf("\nand press Enter. Operator can be +, -, * or /.\n");

scanf("%lf %c %lf", &operand1, &oper, &operand2);

scanf("%c", &newline_char);

if (oper != '+' & oper != '-' & oper != '*' & oper != '/')

{

printf("Incorrect operator!\n");

continue;

} /* end if */

switch (oper)

{

case '+' :

result = operand1 + operand2;

break;

case '-' :

result = operand1 - operand2;

break;

case '*' :

result = operand1 * operand2;

break;

case '/' :

result = operand1 / operand2;

} /* end switch */

printf("%f %c %f = %f\n", operand1, oper, operand2, result);

printf("Another expression? (y/n): ");

scanf("%c", &another_expression);

} while (another_expression == 'y' || another_expression == 'Y');

/* end do-while */

The first if statement in the loop body checks whether the operator entered by the user is +, -, *, or /. If not, it prints the message "Incorrect operator!", and because of the continue statement in the then-part of the if statement, it skips the rest of the loop, evaluates the loop control condition, and proceeds with the next cycle of repetition.

ghhoSMJK DindingsPage 1