Tuan Nguyen
Tuan Nguyen

Reputation: 197

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?

Upvotes: 3

Views: 10576

Answers (4)

Mysticial
Mysticial

Reputation: 471199

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

Upvotes: 8

Pawan Sharma
Pawan Sharma

Reputation: 3334

In the while loop you didn't increment i, but in your for loop you are using

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

You are incrementing i with one and multiplying i by 2 in each iteration of your loop. This is the reason you are getting weird result.

Try the following code for the same result as while loop is generating.

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

Upvotes: 1

Gabe
Gabe

Reputation: 50493

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

Upvotes: 3

icktoofay
icktoofay

Reputation: 128991

The for loop doubles i and then increments it. The while loop only doubles it.

Change the for loop to this:

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

Upvotes: 13

Related Questions