Repetition
·One or more instruction repeated for
certain amount
of time
·Repetition/looping operation:
– For
– While
– Do-while
1. For
•Syntax:
for(exp1;
exp2; exp3) statement;
or:
for(exp1;
exp2; exp3){
statement1;
statement2;
…….
}
exp1
: initialization
exp2
: conditional
exp3
: increment or
decrement
exp1,
exp2 and exp3 are optional
EXAMPLE :
Program to print out numbers from 1 to 10
#include<stdio.h>
int
main()
{
int x;
for( x = 1
; x <= 10
; x++ )
printf( "%d\n", x );
return(0);
}
2. While
•Syntax
:
while
(exp) statements;
or:
while(exp){
statement1;
statement2;
…..
}
EXAMPLE :
int counter = 1;
while ( counter <= 10 ) {
printf( "%d\n", counter
);
++counter;
}
3. Do-While
•Syntax
:
do{
< statements >;
}
while(exp);
•Keep
executing while exp is
true
•exp
evaluation done after executing the statement(s)
EXAMPLE :
int counter=0;
do {
printf( "%d ", counter );
++counter;
} while (counter <= 10);
No comments:
Post a Comment