post increment operator running a for loop into infinite loop - loops

int i;
for(i=0; i<10; )
{
i=i++;
printf("Hello\n");
}
the following code is running into infinite loop. Can any one help me understand why?

Its an infinite loop due to the line i = i++ which works as follows. (Suppose i = 1)
1) 'i' is increased by 1. (So i = 2)
2) The value of i++ i.e. value before increment is assigned to 'i'. (So i = 1)
So, the value of 'i' won't change, condition 'i < 10' will never be false thereby leading to an infinite loop.

Related

Why no output when index value is 0

Change the value of index from o to 1. loop is printing value. Why it is not printing any value when index is assigned to 0?
Currently i = 0 - No Output
Make i = 1 - infinite loop
#include<stdio.h>
int main()
{
for(int i = 0;i++;i<100)
{
printf("Mahesh\n");
}
}
enter code here
C for loop structure:
for ( init; condition; increment )
You have actually added i++ in the place of condition and i<100 in the place of increment.
Flow Control of for loop in C:
init step is executed first and only once.
Condition is evaluated next and if it is True, the body of the loop is executed. If False, the body of the loop doesn't execute and the flow jumps to the next statement after the for loop.
After the body of the loop executes once, the flow control jumps to increment statement and then condition is evaluated again.
Body of loop, Condition and increment steps are repeated in the same order till the condition becomes False after which the for loop terminates.
Your loop is:
for(int i = 0;i++;i<100)
In this, you have i++ as the condition. Now, in this i is evaluated first followed ++. Since, i is 0, it leads to the loop exiting as the condition evaluates to False. But, if you change i to 1, the condition (i.e. i) evaluates to True and it enters the loop.
If you have not done this deliberately, you need the loop like below:
for (int i = 0; i < 100; i++)
The syntax for a for loop in C is as follows:
for ( init; condition; increment ) {
statement(s);
}
-init: initialising the index variable with the value you would like to start the iteration at.
-condition: the condition for the iteration to continue until met
-incremenet: indicating how much you want the program to incremenet your index by
Hence in your example is should be:
for(int i = 0; i < 100; i++){
//yourcode
}
Hope that helps
The parameters of for loop are:
for(initialization; Condition; Next iteration initialization){
//code
}
The initialization(s) can be more than one separated by commas.
The condition will continue if have 1 (or the value TRUE which means the same thing as 1) or will break if the condition is not met i.e the value 0 (or FALSE). You can have multiple conditions as well by the use of && or || or commas.
The third parameter is what you want to do in the next iteration. It can have multiple commands too. I suggest you run the following code and change it to observe the results:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j;
for( i=0,j=0;i<10 || j<5;i++,j++)
printf("%d\t%d\n",i,j);
return 0;
}
#include<stdio.h>
int main()
{
int i = 0;
// Postfix Increment Operator
for (i = 0; i++; i<100) // Condition is false, Because the i is Zero
{
printf("Mahesh");
}
printf("%d", i); // i outputs One here
// Prefix Increment Operator
for (i = 0; ++i; i<100) // Condition is True, Because the i is One
{
printf("Mahesh");
}
}

An example of for loop in C leading to an infinite loop

The following program was cited as going into an infinite loop:
#include<stdio.h>
int main()
{
int n;
for(n = 7; n!=0; n--)
printf("n = %d", n--);
getchar();
return 0;
}
On analyzing, I do find that at one point the value of n does become 0 and right then, the loop should terminate.
Won't it happen such that when it enters the loop for the first time, the value is 7, then it becomes 6, and since that there are 2 post-decrements per iteration?
But, why does that not happen?
Each loop iteration actually decreases n by two, and the comparison n != 0 always sees an odd value for i and hence never terminates.
In particular, just before the iteration in question, n is first decremented to 1 by n-- in the loop header (since this must occur after the end of the previous iteration, just before evaluation of the condition n!=0).
Then, printf("n = %d", n--); is evaluated, printing n = 1, while postdecrementing n to zero. After the end of the loop body, n is decremented again by n-- in the loop header, making it -1, just before the condition n!=0 is evaluated to determine whether the loop should continue.
As a result, n!=0 is true every time it is evaluated (in particular, it is not evaluated at the instant that n is zero, since the n-- in the loop header must first complete)
It's because of the second decrement in the print here:
for(n = 7; n!=0; n--)
printf("n = %d", n--);
That makes the sequence of checks against n go 7, 5, 3, 1, -1, ... There are an even number of values for an int so this will form a cycle upon underflow that leaves out the even numbers, including 0.
Remember that the for loop condition is evaluated just before each loop iteration, and after the decrement in the loop itself. It isn't tested while the loop is running.
try doing this
#include<stdio.h>
int main()
{
int n;
for(n = 7; n>=0; n--)
printf("n = %d", **--n**);
getchar();
return 0;
}

Incrementing of variable inside a loop

What will be the output of the program?
#include<stdio.h>
void main()
{
int i = 0;
while(i < 10)
{
i++;
printf("%d\n",i);
}
}
Will the output start from 0 or from 1 as I my professor taught me that the value of the variable is incremented only at the end of the loop while using i++ unlike in ++i?
The side effect of incrementing using either the prefix ++ or the postfix ++ occurs before the statement i++; completes. The fact that the statement is in a loop doesn't change that.
Your professor is correct. The first time printf is called in the loop, i will have the value 1 because the previous statement incremented the value.
Had you instead had the following code:
while(i < 10)
{
printf("%d\n",i++);
}
Then 0 would be printed on the first iteration. In this case, the value of i is incremented, but the postfix ++ operator means that the old value of i is passed to the printf call.
will start from 1 since the line i++ ends before you enter the next line which prints, the ++i compared to i++ is different when you increment it while doing something else in the same line/command.
for example: if you use
printf("%d",i++);
it would print 0 before incrementing i but if you put it like this:
printf("%d",++i);
it will first increment i (from 0 to 1) and then print i(which is 1 the first time it's printed).
Your code will print 1 as first value.
i++ increments the value at the end of the statement, and vice versa ++i increments the value before the statement. This is usually used when assigning variables:
i = 5;
int a = ++i; // a=6, i=6
i = 5;
int b = i++; // b=5, i=6

Variable assignment in conditional statement

I have a code:
while (i = j) {
/* not important */
}
For how long will this while loop work? Is it till the moment when the value of variable j is equal to zero?
For while loop properties, quoting C11, chapter §6.8.5/p4, (emphasis mine)
An iteration statement causes a statement called the loop body to be executed repeatedly
until the controlling expression compares equal to 0. [...]
and considering the assignment inside the loop condition, quoting §6.5.16/p3
[...] An
assignment expression has the value of the left operand after the assignment,111) but is not
an lvalue. [...]
So, every time the loop condition is executed, first the current value of j will be assigned to i and then, the value of i will be taken as the controlling expression value.
In other words, the loop will continue until j becomes 0.
That said, iff you are sure about the assignment part as the loop condition statement, put it into double parenthesis like
while ((i = j)){
Less confusion for the compiler and the next developer/maintainer.
For how long will this while loop work? Is it till the moment when the value of variable j is equal to zero?
A while loop would would work till it's the condition or expression evaluates to be false (i.e, 0).
In your code, YES while loop works till the moment when the value of variable j is equal to 0.
Note : The assignment operator in C returns the value of the variable that was assigned i.e, the value of the expression i = j os equal to j.
In while(i = j) , first i is assigned with value of jand then the expression is evaluated whether true or false.
Why not try a simple program :) :
#include <stdio.h>
int main(void)
{
int i = 0,j =10;
while (i = j)
{
printf("in loop when j = %d\n",j);
j--;
}
printf("exited loop when j = %d",j);
}
output :
in loop when j = 10
in loop when j = 9
in loop when j = 8
in loop when j = 7
in loop when j = 6
in loop when j = 5
in loop when j = 4
in loop when j = 3
in loop when j = 2
in loop when j = 1
exited loop when j = 0
An assignment operation always returns the result of the assignment, so the loop will continue until j == 0, this behavior exists so you can chain many assignment operations together like so:
a = b = c;

Understanding For Loops

I'm trying out a for loop. I added an if statement to stop the loop once it reaches 30.
I have seen that i <= 10 will run 11 times, since the loop will still run when it reaches 10.
Why does the code below run 11 times (first print line) if there is an if statement that sets i back to 0 when it reaches 10? Shouldn't it only print 10 asterisks instead of 11 - since it never reaches the 11th loop? Also, the second if sets i back to 10, which should let the loop run one more time, through the first if, which would and then set the i back to 0?
int j = 0;
for (int i = 0; i <= 10; i++)
{
Console.Write("*");
if (i == 10)
{
j++;
Console.WriteLine("");
i = 0;
}
if (j == 30)
{
i = 10;
}
}
On the first loop, the line has 11 stars, because i iterates from 0 through 10, which is a total of 11 iterations.
Whenever i becomes the value 10, j is incremented, a newline is printed, and i becomes 0.
However, when i is set to 0 within the loop, the loop makes i iterate from 1 to 10, for a total of 10 iterations.
This is because i is incremented just before the next iteration starts.
A for loop with this structure:
for (INIT; CONDITION; INCREMENT) {
BODY
}
is more or less equivalent to this while loop:
INIT
while (CONDITION) {
BODY
INCREMENT
}
The caveat is when BODY has a continue statement, it actually jumps down to the INCREMENT part.

Resources