My question is how come when we use ++ in a 'for loop' (++ on the right side) it increases. And in this example its on the right side but it does not increase.
int a = 1, y;
b = a++; //so "b" will be 1
// if we do ++a then "b" will be 2
My question is how come when we use ++ in a 'for loop' (++ on the right side) it increases. And in this example its on the right side but it does not increase.
int a = 1, y;
b = a++; //so "b" will be 1
// if we do ++a then "b" will be 2
It increases in both the for loop and in your example. a++ increases a, but b gets the previous value of a.
In a for loop you don't assign the return value of i++ to a different variable, so it doesn't matter if you write i++ or ++i.
for (int i=0;i<5;i++)
{
System.out.println(i);
}
and
for (int i=0;i<5;++i)
{
System.out.println(i);
}
Will behave exactly the same.
In both cases, the value of a increase. However, with b = a++;, the value of a increase after its original value has been assigned to b but with b = ++a; the value of a increase before its value is assigned to b.
The distinction is not with the value of a beeing increased or not; it is for the value that is assigned to the variable b: the original value before the increase of a or the new value after its increase.
If there is no assignment of a to some other variable, then there is no difference between a++ and ++a.
in a++, the value of a is incremented after the execution on statement i.e while execution of statement the value is not incremented but is incremented AFTER its execution .
in ++a, the value of a is incremented during the execution of statement i.e while execution we get the incremented value as the result.