Reputation: 197
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
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
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
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