-3
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?

3 Answers3

1

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

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++

Community
  • 1
  • 1
Nick M.
  • 142
  • 4
0

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.

Chen Chen
  • 1
  • 2