How to convert a while loop to a for loop in c

By : Milon
On : 5:10 PM

The basic structure of for loop is as following

for(initialization; condition; adjustment){
        statement(s);
      }

So the fo loop has four parts,

  1. Initialization: We need to assign a value for the control variable.
  2. condition: We have to use a conditional expression here. The compiler execute/iterate the for loop until it get 0 or false
  3. adjustment: Adjust the control variable (by increment or decrement ) so that the condition get 0 or false
  4. statement(s): Any type of simple or compound statement(s)

The basic structure of while loop is as following

while(condition){
        statement(s);
      }

We can see that the while loop has only two parts

  1. Condition
  2. statement(s)

So if we wish to use the while loop as the for loop we need to construct it as the following

initialization;
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;
}