Why is the for loop turning into an infinite loop? - c

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.)

i++ is excecuted at the end of the loop so i will become 13

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.

Related

Issue in incrementing numbers in Do while loop

I'm learning and tinkering with the C programming language. Unfortunately, While learning and playing with the do-while loop, I'm confused. I wrote and ran a program to increment a variable from 1 to 100 with condition i<=100; the code ran successful, but when I changed the condition of the do-while loop to i==100, the output confuses me because only 1 is printed on the console. Please help.
The code below gives the expected output.
#include<stdio.h>
int main(){
int i=1;
do{
printf("\n%d\n",i);
++i;
} while(i<=100);
}
The code below gives output 1.
#include<stdio.h>
int main(){
int i=1;
do{
printf("\n%d\n",i);
++i;
} while(i==100);
}
Thank you.
The second one loops if i == 100. It is not the truth (as i == 1) on the first iteration and loop exits.
The do-while loop always executes once and then checks whether the condition holds true. If the condition is true, the loop executes again and then checks the condition.
In your case, the mandatory first pass prints the value of i and then increments it. Next, the condition is checked while(i==100). At this point, i is 2 and the condition fails resulting in the loop being terminated.

C loop while - beginner

My first question here on forum. I'm not sure why the output of the code is "hi" whereas I'm thinking it should be null. I might be missing here something badly. Help appreciated.
#include <stdio.h>
int main(void)
{
int i = 0;
while (i == 0)
{
printf("hi\n");
i++;
}
}
Your while loop will run what you have enclosed in it up until the stopping condition is false. you have int i = 0 as your starting value and your while loop condition says while (i == 0) to print "hi". Since i = 0, your condition is true one time and will print "hi" once before i increments and becomes false on the next pass.
The output of your code is correct, the while loop is entered because i == 0 and then i changes to 1 so the condition is false on the second iteration which makes the loop end and thus the program too.
You are confusing while loops with until loops (which C doesn't have). The while loop will execute its body while a condition is true, not until it is true. So if you want to print "hi" 10 times, you will need to write
int i = 1;
while (i <= 10) {
printf("hi\n");
++i;
}
#include <stdio.h>
int main(void)
{
int i = 0;
while (i == 0)
{
printf("hi\n");
i++;
}
}
while loop works in such a way that the loop executes only if the condition inside the parenthesis is true. In the above code, the value of 'i' is initially set to 0, which satisfies the condition of the while loop. It enters inside the loop, goes on to print 'hi' and then increments the value of 'i'.
Now the condition of while is again checked. Since the condition fails this time ,as the value of 'i' has been incremented, it exits out of the loop and the program terminates. I hope it answers your question.
like #iharob said, i==0 returns 1 which creates an infinite loop running and printing hi hi hi hi hi
if i was to do them, I would put in an if statement inside the while loop to check if i is still 0 or changed. if its 0, print hi, else, return 0;
it is obvious that the syntax that your are looking for is a do ... while loop
because programs run from up to down and left to right, the moment that your program reaches the while checks the i and it is still 0 but for the next loop it won't print anything because i=1.

what happens when increment counter and test counter are interchanged in for-loop syntax? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
please explain why
Case 1:
int main()
{
int i;
for(i=1;i++;i<100)
printf("%d",i);
return 0;
}
results in infinite loop, whereas
Case 2:
int main()
{
int i;
for(i=0;i++;i<100)
printf("%d",i);
return 0;
}
Doesn't run the loop even once?
Please clarify how to interpret this kind of syntax?
The syntax of a for loop in C programming language is:
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop:
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
In First Case:
init set i = 1
conditon - here i = 1 which is true in c. (Post increment increases the value after execution of statment)
body - executes printf("%d",i);
increment - i<100 which is not affecting the value of i.
Now In C for all values from 1 to infinity, its value is true, hence executing infinetly
In Second Case
init set i = 0
conditon - here i = 0 (again Post Increment) which is false in c, therefore the loop gets exit.
Hence it is not executing even once.
Flow diagram of For Loop :
The proper syntax is
for (i=1; i<100; i++) {
something
}
What's actually happening?
The for loop takes three arguments,
1. The initial condition, or initialization that happens at the beginning, before the loop is executed. In this case it's i=1 that is set i as 1
2. The final condition that is checked at the beginning of every loop. If this condition is not met, the loop is broken. In this case it's i<100. So, if at the start of next loop, when i >= 100 the loop is broken.
3. The step or periodic operation at the end of loop. In this case it's i++. At the end of every loop i is incremented by 1.
What's happening with your code
for (i=1; i++; i<100)
The first part is good.
The second is executed at the beginning of each loop. i++ returns the value of i then increments it. (In contrast to ++i, which does the opposite.) Since in your first example i=1, it starts at one, and the second argument always returns a value >= 1 which is interpreted as true. But in your second example, i starts at 0. So during first iteration the second argument returns 0, which is interpreted as false, and the loop never starts.
The third one is executed at the end, and never affects the loop in any way.
int main()
{
int i;
for(i=0;i++;i<100)
printf("%d",i);
return 0;
}
as for loop is having syntax
for(initialize variable; condition check; increment/decrement)
you have initialize variable as i = 0
in condition checking part you have written i++ i.e post increment so i remain 0 which means FALSE and hence it will exit for loop.
Try this :
int main()
{
int i;
for(i=0;i<100;i++)
printf("%d",i);
return 0;
}

Can an empty for-loop be "correct"?

I have a doubt about the for loop of the following code in C:
main()
{
int i=1;
for(;;)
{
printf("%d",i++);
if(i>10)
break;
}
}
I saw this code in a question paper. I thought that the for loop won't work because it has no condition in it. But the answer says that the code has no error. Is it true ? If true, how ?
The regular for loop has three parts:
Initialization
Condition
Increment
Usually they are written like this:
for (initialization; condition; increment) { statements }
But all three parts are optional. In your case, all parts are indeed missing from the for loop, but are present elsewhere:
The initialization is int i=1
The condition is if (i>10) break
The increment is i++
The above code can be equivalently written as:
for (int i=1; i <= 10; i++) {
printf("%d", i);
}
So all the parts necessary for a for loop are present, except they are not inside the actual for construct. The loop would work, it's just not a very readable way to write it.
The for (;;) loop is an infinite loop, though in this case the body of the loop takes actions that ensure that it does not run forever. Each component of the control is optional. A missing condition is equivalent to 1 or true.
The loop would be more clearly written as:
for (int i = 1; i < 11; i++)
printf("%d", i);
We can still debate whether the output is sensible:
12345678910
could be produced more easily with:
puts("12345678910");
and you get a newline at the end. But these are meta-issues. As written, the loop 'works'. It is syntactically correct. It also terminates.
You are not specifying any parameters or conditions in your for loop, therefore, it would be an endless loop. Since there is a break condition based on another external variable, it would not be infinite.
This should be re-written as:
for (int i = 1; i <= 10; i++)
printf("%d",i++);
It's an infinite loop. When there is not a condition in for and we use ;; the statements in the body of for will be executed infinitely. However because there is a break statement inside it's body, if the variable i will be greater than 10, the execution will be stopped.
As it is stated in MSDN:
The statement for(;;) is the customary way to produce an infinite loop which can only be exited with a break, goto, or return statement.
For further documentation, please look here.
Even if a for loop is not having any condition in it, the needed conditions are specified inside the for loop.
The printf statement has i++ which keeps on increasing the value of i and next we have if statement which will check if value of i is less than 10. Once i is greater than 10 it will break the loop.

for(++i;++i;++i) the second argument is < or <=?

In this for loop statement
#include<stdio.h>
int main()
{
static int i;
for(++i;++i;++i) {
printf("%d ",i);
if(i==4)
break;
}
return 0;
}
Variable i is at first 0. The arguments in the for-loop at 1st round are 1st ++i: i = 0 + 1 = 1 2nd ++i: i=1+1=2 So, in first loop I have this for(i=1; i<2; ++i); or for(i=1; i<=2; ++i);?EDIT I found this example online in a test about C. I run this (inside the for-loop , I have a break point so after some loops it breaks) but I was just guessing the behavior of that so I asked it here to be sure. I am learning now C so stupid questions exists for me. Its better to ask, than not.
In the second argument it is actually ++i!=0, The loop is interpreted as
for(++i;++i!=0;++i)
If you start with a positive i or 0, it will be an infinite loop and will invoke undefined behavior when i reaches INT_MAX.
If i was -Ve initially the loop may stop at a defined run.
EDIT: As you changed your question, Your code will not crash, but you can clearly understand the dry-run by replacing the second ++i with ++i!=0.
So the 1st iteration becomes:
(i=1;2!=0;++i/*this will execute later*/)
2nd iteration becomes:
i=3 //this is from the 1st iteration last part.
(/*initialization is done 1st time only*/;4!=0;++i/*again, this will execute after this iteration*/)
It will print 2 4.
Before the for loop, i will be 0. It hasn't been assigned anything yet, and static variables are guaranteed to be zero initialized before they are first used.
It will execute the first ++i in the for loop, since that expression is evaluated once at the beginning of the loop. i will be 1.
It will execute the second ++i, because that is evaluated BEFORE every loop to see if it should run an iteration of the loop. i will be 2.
It will run the loop body. This will print 2.
The if condition won't be true so it won't break.
It will execute the third ++i in the for loop statement, since it evaluates that AFTER every iteration. i will be 3.
It will execute the second ++i again, since it needs to see if it needs to run another loop. It will be nonzero, so it will run another loop. i will be 4.
It will print 4.
The if condition will be true, it will break out of the loop.
However, it is a nonsense way to do it. This is a more appropriate way to do that:
int i;
for (i = 2; i <= 4; i += 2)
printf("%d ", i);
or better yet:
printf("2 4 ");
static int i;
While the C standard guarantees that variables with static storage duration are initialized to 0, you should not abuse that. Always initialize your variables, either at the line where they are declared or in runtime. So change this to static int i=0;
The first ++i is indeed equivalent to having i=1 there. Esentially your loop does this:
for(i=1; loop_until_program_crash; i++)
If you have a break inside the loop, then the loop is likely poorly written. If you know in advance when the loop should end, then that condition should be inside the for loop condition. If you don't know in advance, then use a while loop instead.
It should be :
for(i=1; i<=2; ++i);
static int i=0;
for(++i;++i<=2;++i)
{
printf("4rth :%d\n",i);
}
see : http://ideone.com/TGLYlL

Resources