The basic structure of for loop is as following
statement(s);
}
So the fo loop has four parts,
- Initialization: We need to assign a value for the control variable.
- condition: We have to use a conditional expression here. The compiler execute/iterate the for loop until it get 0 or false
- adjustment: Adjust the control variable (by increment or decrement ) so that the condition get 0 or false
- statement(s): Any type of simple or compound statement(s)
The basic structure of while loop is as following
statement(s);
}
We can see that the while loop has only two parts
- Condition
- statement(s)
So if we wish to use the while loop as the for loop we need to construct it as the following
while( condition){
statement(s);
adjustment;
}
Now lets see a program using both for loop and while loop. See the factorial finding program using both for loop and while loop
#include<stdio.h> int main(void){ int count; printf("Using for loop\n\n"); for(count = 1;count<=5; count++){ printf(" \t count is %d\n",count); } printf("\n Using for loop\n\n"); count = 1; while(count<=5 ){ printf("\t count is %d\n",count); count++; } return 0; }