Professional Documents
Culture Documents
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Looping – basics
while loop
for loop
OR
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
i = 1;
while(i<=rows){
j = 1;
while(j<=i){
printf("* ");
j++;
}
printf("\n");
i++;
}
BITS Pilani, Pilani Campus
Exercises
Print this pattern on your
while(k != 2*i-1){
screen using loops.
printf("* ");
No. of rows are user input. k++;
int i, space, rows, k=0; }
printf("Enter number of printf("\n");
rows: ");
i++;
scanf("%d",&rows);
k=0;
i = 1;
}
while(i<=rows) {
space = 1;
while(space<=rows-i){
printf(" ");
space++;
}
1
23
456
7 8 9 10
do {
statement(s);
} while( condition );
int num=10;
for ( ;num<20; num++)
for( ; ; )
int count;
for (count=1; count<=3; count++);
printf("%d\n", count);
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j)
printf("* ");
printf("\n");
}
BASIS FOR
FOR WHILE
COMPARISON
Declaration for(initialization; while ( condition) {
condition; iteration){ statements; //body of loop
//body of 'for' loop } }
Format Initialization, condition checking, iteration Only initialization and condition checking is
statement are written at the top of the done at the top of the loop.
loop.
Use The 'for' loop used only when we already The 'while' loop used only when the number
knew the number of iterations. of iteration are not exactly known.
Condition If the condition is not put up in 'for' loop, If the condition is not put up in 'while' loop,
then loop iterates infinite times. it provides compilation error.
Initialization In 'for' loop the initialization once done is In while loop if initialization is done during
never repeated. condition checking, then initialization is
done each time the loop iterate.
Iteration In 'for' loop iteration statement is written at In 'while' loop, the iteration statement can
statement top, hence, executes only after all be written anywhere in the loop.
statements in loop are executed.