Why is the code below resulting in an infinite loop?
#include <stdio.h>
void main()
{
int i;
for(i=0;i!=12;i++)
{
printf("%d\n",i);
i=12;
}
}
Why is the code below resulting in an infinite loop?
#include <stdio.h>
void main()
{
int i;
for(i=0;i!=12;i++)
{
printf("%d\n",i);
i=12;
}
}
Because i
never equals 12
when it's checked by the loop. You execute i++
after each loop iteration, so i
always equals 13
when it's checked.
You can omit the i++
part entirely, or set i = 11;
instead to accomplish the same thing. (Of course, since "the same thing" in this case is only ever wanting a single iteration of the loop, you don't really need a loop in the first place. But I assume this is just a contrived learning exercise.)
It happens because the for
loop increments the variable before checking the loop condition.
Here's the code with the for
loop rewritten as a while
loop:
#include<stdio.h>
void main()
{
int i;
i=0;
while(i!=12)
{
printf("%d\n",i);
i=12;
i++;
}
}
And here's its output (the first few lines):
0
13
13
13
...
Each time through the loop, the code sets i
to 12, and then immediately increments it to 13 before checking the condition and restarting the loop. The loop will only terminate when i==12
, so it will run forever.