int num=0
for(int i=0;i<5;i++)
{
num = num++;
system.out.println(num);
}
I am little confused with the output of above program. It prints five times 0 in output. Why isn't the num
variable incremented in the loop?
int num=0
for(int i=0;i<5;i++)
{
num = num++;
system.out.println(num);
}
I am little confused with the output of above program. It prints five times 0 in output. Why isn't the num
variable incremented in the loop?
num++
will return the current value of num
(i.e., 0), and then increment num
. However, since you re-assign this to num
, you overwrite the incrementation with the previous value, so num
remains 0
throughout the program.
You need to increment with ++num. For example:
int num=0;
for(int i=0;i<5;i++)
{
num = ++num;
}
System.out.println(num);
Output:
5
Though you don't need to reassign it every time, num++
alone would be the proper way to do it.
See previous answer: Difference between ++var and var++
You should know the difference between num++
and ++num
. In your case, at first num
is set to 0. When you say num = num++;
, it first assgin 0 to num
(left one), and then apply ++. It really does not matter what the right part of equation does... So that's the reason you've got 5 0's.