cfor-loopwhile-loop

Translate a while loop into for loop


Have a simple while loop and trying to make it to a for loop

i=1
while(i<=128)
{     printf("%d",i);
   i*=2;
}

Here is my for loop

for (i=1;i<=128;i++)
{ 
   printf("%d",i);
   i*=2;
}

How come it does not give the same output? The first one would print 1248163264128, the for loop print 137153163127?


Solution

  • Because you're also incrementing i in the for-loop. In your original while-loop, i is never incremented.

    Try this:

    for (i=1; i<=128; i*=2)  //  Remove i++, move the i*=2 here.
    {
        printf("%d",i);
    }