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.

Recommended Answers

All 2 Replies

It has little to do with your increment process but with your do-while loop

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.