3

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?

2
  • 2
    Increment i*=2 in for (i=1;i<=128;i*=2) Commented Oct 16, 2011 at 2:31
  • condition in for loop is wrong.. Placing i*=2 in place of i++ solves your issue.. Commented Jan 3, 2013 at 19:18

4 Answers 4

13

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);
}
Sign up to request clarification or add additional context in comments.

Comments

8

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

2 Comments

No, by all means try this for(i=1; i<=128; i*=2)! Even worse, this answer strengthens the idea that a for loop can only increment a loop variable, which the OP seems to have already.
@ChristianRau Looks like you've stumbled upon a post from my earlier days. Fixed.
3
for (i=1;i<=128;i*=2)
{ 
  printf("%d",i);    
}

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.