• Post Reply Bookmark Topic Watch Topic
  • New Topic

please explain all steps of this program. i dont understand why the result is a-b c-d  RSS feed

 
Williams Tony
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Tony Docherty
Bartender
Posts: 3271
82
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Get a pen and paper and work through each line of the program executing each line in your head and everytime a variable changes value write down the new value.
In this code we only have 1 variable 'x' which changes value which makes things a bit easier - we can ignore the 'args' variable as it isn't used anywhere.

Line 3 - The program execution starts at the main method
Line 4 - x is set to 3
Line 5 - A while loop starts and will continue while x is greater than 0. As we know x = 3 we step into the body of the while loop
Line 6 - As x is greater than 2 we step into the body of the if statement
Line 7 - print "a"
Line 8 - end of if body
Line 9 - subtract 1 from x so x now equals 2
Line 10 - print "-"
Line 11 - As x equals 2 we step into the body of the if statement
Line 12 - print "b c"
Line 13 - end of if body
Line 11 - As x does not equal 1 we jump over the body of the if statement
Line 13 - end of if body
Line 14 - end of while body so jump back to Line 5
Line 5 - Test the while condition, x = 2 which is greater than 0 so we step into the body of the while loop
Line 6 - ....

I'll leave you to work the rest out
 
John Joe
Ranch Hand
Posts: 427
3
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Add System.out.println(x); in each line of code to check the value of x. Maybe you will have better understanding after this.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!