Home > Enterprise >  How do i convert for loop to while loop in c language?
How do i convert for loop to while loop in c language?

Time:04-28

#include<stdio.h>
int main(){
  int i,j,rows;
  printf("Input number of rows : ");
  scanf("%d",&rows);
  for (i=1;i<=rows;i  ) {
    for (j=1;j<=i;j  )
      printf ("%d",i);
    printf ("\n');
  }
return 0;
}

I am new to c programming can anyone help to convert this for loop into while loop? Thanks

CodePudding user response:

Any for loop as:

for (e1; e2; e3) {
    *block*
}

is strictly equivalent to (only if there is no continue in the block):

e1;
while (e2) {
    *block*
    e3;
}

If e2 is empty, then it could be replaced by 1 during translation.

CodePudding user response:

So you have this loop:

for (i=1;i<=rows;i  ) 
{
    for (j=1;j<=i;j  )
      printf ("%d",i);
    printf ("\n');
  }

This loop keeps running until 1: i reach i <= rows and 2: j<=i. To change the for loop into a while loop, you only need to use an equivalent expression. You can try this way for the first loop:

     i=1;
     while(i<=rows)
    {
     [...]
     i  ;
    }

You just have to manually set before the loop and increase just before the end of the loop the counter variable. And for the loop inside the first loop, you just do the same thing:

i=1    
while(i<=rows)
{
   j=1
   while(j<=i)
   {
      [...]
      j  ;
   }
 }
    
    
        
  • Related