-3

enter image description here

I have a java example, I know it's very easy, but I'm just a beginner. I have a problem in line 8 and 9:

while (tailFeathers > 1){
System.out.print(--tailFeathers + " ");}

I think it will print "5 2" because 1 is not greater than 1, but the answer is E, which is "5 2 1". Could u explain to me? Am I wrong or strange result? Thanks so much.

Nope Nope
  • 19
  • 7

3 Answers3

3

Follow the logic closely

It seems you agree that that at line 7. The output to the screen is "5 "

At this point tailFeathers = 3

3>1 so enter the loop, decrement tailFeathers before using it.

So the screen output is now "5 2 "

At this point tailFeathers = 2

2>1 so enter the loop, decrement tailFeathers before using it.

So the screen output is now "5 2 1"

at this point tailFeathers = 1

1=1 don't enter the loop

screen output is "5 2 1"

Dharman
  • 30,962
  • 25
  • 85
  • 135
mitchell
  • 298
  • 1
  • 11
0

I think it will print "5 2" because 1 is not greater than 1, but the answer is E, which is "5 2 1". Could u explain to me?

You are correct in thinking that the loop body will not be entered when tailFeathers==1, but you misunderstand what will be printed.

Here's the loop:

while (tailFeathers > 1) {
     system.out.print(--tailFeathers + " ");
}

Let's suppose that the loop body was entered because tailFeathers==2 which is > 1. The system.out.print(--tailFeathers + " ") statement will do several things in a well defined order:

  1. It will decrement the value of tailFeathers (i.e., it will set tailFeathers=1),
  2. It will call library functions to create a new String, "1", to express the new, decimal value of tailFeathers,
  3. It will concatenate the string "1" with the string " " to create a new string, "1 ", and then finally,
  4. It will call system.out.print("1 ").

The key concept here is the meaning of --tailFeathers. The value of that expression is the value of tailFeathers after the variable has been decremented.

If you changed it to tailFeathers--, you'd get a different result. In that case, the value of the expression is the value that tailFeathers had before it was decremented (i.e., 2 in my example, above.)

The way to remember this is to read it from left to right:

  • --t means first, decrement t, then use the new value of t, and
  • t-- means first, use the original value of t, and then some time later, decrement t.
Solomon Slow
  • 25,130
  • 5
  • 37
  • 57
0

--counter => counter = counter-1. Its value gets updated instantly and this is how the the pre operator works. Also, remember there is while loop in the last, so it prints recursively until the condition becomes false.