0

int x=10;
int total=10;
do {
total += x++;
}while(x<15);
System.out.println(x);

The output of this program will be 15. I don't understand why 15 is the answer.

I'm not understanding the arithmetic here. Doesn't the "+=" mean total = total + x? And doesn't x++ mean that the next value for x will be x+1?

I don't see why this would not output 20 on the first go around. 21 on the second go around, etc.

3
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by ~s.o.s~
0

int x=10;
int total=10;
do {
total += x++;
}while(x<15);
System.out.println(x);

The output of this program will be 15. I don't understand why 15 is the answer.

I'm not understanding the arithmetic here. Doesn't the "+=" mean total = total + x? And doesn't x++ mean that the next value for x will be x+1?

I don't see why this would not output 20 on the first go around. 21 on the second go around, etc.

A rewrite:

int total = 10, x = 10;
do {
  total = total + x;
  x++;
} while(x < 15);
System.out.println("x -> " + x);

Output: x -> 15
int total = 10, x = 10;
do {
  total = total + x;
  x++;
  System.out.println("total -> " + total);
} while(x < 15);

output:
  total -> 20
  total -> 31
  total -> 43
  total -> 56
  total -> 70

Hope you do realize what you are doing wrong here...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.