Post Increment Operator Not Incrementing in for Loop

Post increment operator not incrementing in for loop

for (int i = 0; i < 10; i = i++) {

The above loop is essentially the same as: -

for (int i = 0; i < 10; i = i) {

the 3rd part of your for statement - i = i++, is evaluated as: -

int oldValue = i; 
i = i + 1;
i = oldValue; // 3rd Step

You need to remove the assignment from there, to make it work: -

for (int i = 0; i < 10; i++) {

(On OP request from Comments)

Behaviour of x = 1; x = x++ + x++; : -

As far as your issue as specified in the comment is concerned, the result of the following expression: -

x = 1; 
x = x++ + x++;

is obtained as follows: -

Let's mark different parts of the second statement: -

x = x++ + x++;
R A B

Now, first the RHS part (A + B) will be evaluated, and then the final result will be assignmed to x. So, let's move ahead.

First A is evaluated: -

old1 = x;  // `old1 becomes 1`
x = x + 1; // Increment `x`. `x becomes 2`
//x = old1; // This will not be done. As the value has not been assigned back yet.

Now, since the assignment of A to R is not done here, the 3rd step is not performed.

Now, move to B evaluation: -

old2 = x;  // old2 becomes 2. (Since `x` is 2, from the evaluation of `A`)
x = x + 1; // increment `x`. `x becomes 3`.
// x = old2; // This will again not be done here.

Now, to get the value of x++ + x++, we need to do the last assignment that we left in the evaluation of A and B, because now is the value being assigned in x. For that, we need to replace: -

A --> old1
B --> old2 // The last assignment of both the evaluation. (A and B)

/** See Break up `x = old1;` towards the end, to understand how it's equivalent to `A = old1; in case of `x = x++`, considering `x++ <==> A` in this case. **/

So, x = x++ + x++, becomes: -

x = old1 + old2;
= 1 + 2;
= 3; // Hence the answer

Break up of 3rd part of x = x++, to see how it works in x = x++ + x++ case: -

Wonder why the replacement is done as A --> old1 and not x --> old1, as in case of x = x++.

Take a deep look at x = x++ part, specially the last assignment: -

x = oldValue;

if you consider x++ to be A here, then the above assignment can be broken into these steps: -

A = oldValue;
x = A;

Now, for the current problem, it is same as: -

A = old1;
B = old2;
x = A + B;

I hope that makes it clear.

Post-increment and pre-increment within a 'for' loop produce same output

After evaluating i++ or ++i, the new value of i will be the same in both cases. The difference between pre- and post-increment is in the result of evaluating the expression itself.

++i increments i and evaluates to the new value of i.

i++ evaluates to the old value of i, and increments i.

The reason this doesn't matter in a for loop is that the flow of control works roughly like this:

  1. test the condition
  2. if it is false, terminate
  3. if it is true, execute the body
  4. execute the incrementation step

Because (1) and (4) are decoupled, either pre- or post-increment can be used.

In a for loop, is there a difference between pre/post-incrementing a loop control variable in terms of the total quantity of iterations?

There is no difference. In older compilers, ++counter was faster because it did not create a temporary variable but all modern compilers can optimize that out. For heavy objects with custom (non-inlined) increment operators, ++counter can still be more efficient.

As for when evaluation takes place:

for (initialization; condition; increment/decrement)
code;

is evaluated as

{
initialization;
while (condition)
{
code;
increment/decrement;
}
}

for loop resulting in infinite loop, when post increment is used

In your code, i++ returns the "old" value of i (the value it had before incrementing it). This old value is then assigned to i. So after i = i++, i has the same value as before.

Why doesn't changing the pre to the post increment at the iteration part of a for loop make a difference?

The loop is equivalent to:

int x = 2;
{
int y = 2;
while (y > 0)
{
System.out.println(x + " "+ y + " ");
x++;
y--; // or --y;
}
}

As you can see from reading that code, it doesn't matter whether you use the post or pre decrement operator in the third section of the for loop.

More generally, any for loop of the form:

for (ForInit ; Expression ; ForUpdate)
forLoopBody();

is exactly equivalent to the while loop:

{
ForInit;
while (Expression) {
forLoopBody();
ForUpdate;
}
}

The for loop is more compact, and thus easier to parse for such a common idiom.

Need to understand for loop better - post increment operator

What you're missing is when each of those sections of the for statement happen:

for (int i = 0 ; i < 3 ; i++)
// 111111111 22222 333
  • The first bit happens once before any iterations are done.
  • The second expression is evaluated before each potential iteration and, if false, no further iterations are done.
  • The third bit is done at the end of each iteration, before returning to evaluate the second bit.

Now re-read that last bullet point carefully. The i++ is done at the end of an iteration, after the cout << i. And, immediately after that, the continuation condition is checked (the second part).

So the loop is effectively the same as:

{   // Outer braces just to limit scope of i, same as for loop.
int i = 0;
while (i < 3) {
cout << i;
i++;
}
}

That's why you get 0 1 2.

Difference between pre-increment and post-increment in a loop?

a++ is known as postfix.

add 1 to a, returns the old value.

++a is known as prefix.

add 1 to a, returns the new value.

C#:

string[] items = {"a","b","c","d"};
int i = 0;
foreach (string item in items)
{
Console.WriteLine(++i);
}
Console.WriteLine("");

i = 0;
foreach (string item in items)
{
Console.WriteLine(i++);
}

Output:

1
2
3
4

0
1
2
3

foreach and while loops depend on which increment type you use. With for loops like below it makes no difference as you're not using the return value of i:

for (int i = 0; i < 5; i++) { Console.Write(i);}
Console.WriteLine("");
for (int i = 0; i < 5; ++i) { Console.Write(i); }

0 1 2 3 4

0 1 2 3 4

If the value as evaluated is used then the type of increment becomes significant:

int n = 0;
for (int i = 0; n < 5; n = i++) { }

Control flow for a while loop with post increment

You are using post increment

while (i++ <= 10) { // i will be incremented after evaluating i and do comparaison with 10
i++;
}

You can use the pre increment instead of post increment

while (++i <= 10) { // i will be incremented before comparaison
i++;
}

And the value of i will be 11.

Can a for loop increment/decrement by more than one?

Use the += assignment operator:

for (var i = 0; i < myVar.length; i += 3) {

Technically, you can place any expression you'd like in the final expression of the for loop, but it is typically used to update the counter variable.

For more information about each step of the for loop, check out the MDN article.

java looping example with increment operator

use num++;

int num=0;
for(int i=0;i<5;i++){
num++;
System.out.print(num);
}

Output 12345

num=num++;

is equals to num=num;

num=++num;

is equals to num=num+1;



Related Topics



Leave a reply



Submit