6. Write short notes on the following: (JAN 2009)
for loop
while loop
dowhile loop
Switch case (MAY 2009/FEB 2009/FEB 2010)
1. ITERATION, FOR LOOPS
The basic format of the for statement is,
for( start condition; continue condition; re-evaulation )
program statement;
/* sample program using a for statement */
#include <stdio.h>
main() /* Program introduces the for statement, counts to ten */
{
int count;
for( count = 1; count <= 10; count = count + 1 )
printf(“%d “, count );
printf(“\n”);
}
The program declares an integer variable count. The first part of the for statement for (count = 1; initialized the value of count to 1.
The for loop continues with the condition count <= 10; evaluates as TRUE. As
the variable count has just been initialized to 1, this condition is TRUE and so the
program statement printf(“%d “, count ); is executed, which prints the value of count to the screen, followed by a space character.
Next, the remaining statement of the for is executed count = count + 1); which adds one to the current value of count. Control now passes back to the conditional test, count <= 10; which evaluates as true, so the program statement printf(“%d “, count ); is executed.
Count is incremented again, the condition re-evaluated etc, until count reaches a value of
11.
When this occurs, the conditional test count <= 10; evaluates as FALSE, and the for loop terminates, and program control passes to the statement printf(“\n”); which prints a newline, and then the program terminates, as there are no more statements left to execute
2. THE WHILE STATEMENT
The while provides a mechanism for repeating C statements whilst a condition is
true. Its format is, while( condition ) program statement;
Somewhere within the body of the while loop a statement must alter the value of the condition to allow the loop to finish.
Example:
/* Sample program including while */
#include <stdio.h>
main()
{
int loop = 0;
while( loop <= 10 ) {
printf(“%d\n”, loop);
++loop;
}
}
The above program uses a while loop to repeat the statements
printf(“%d\n”,loop); ++loop; the value of the variable loop is less than or
equal to 10.
3. THE DO WHILE STATEMENT
The do { } while statement allows a loop to continue whilst a condition evaluates as TRUE (non-zero). The loop is executed as least once.
Example:
/* Demonstration of DO...WHILE */
#include <stdio.h>
main()
{
int value, r_digit;
printf(“Enter the number to be reversed.\n”);
scanf(“%d”, &value);
do {
r_digit = value % 10; printf(“%d”, r_digit); value = value / 10;
} while( value != 0 );
printf(“\n”);
}
The above program reverses a number that is entered by the user. It does this by using the modulus % operator to extract the right most digit into the variable r_digit. The original number is then divided by 10, and the operation repeated whilst the number is not equal to 0.