[Solved] How does this program work. Im rookie in programming so please explain it in simplified way


So, the first line is a while-loop it keeps evaluating the statements in between the {} brackets if the condition x<4 is fulfilled.

   while ( x < 4 ) {
  • Let’s assume x = 0
  • x<4 is a true statement so we enter the brackets:

  • System.out.print("a"); will print ‘a’

  • the next line if ( x < 1 ) { is an if statement, it will evaluate the code in the brackets once if the condition (x < 1) is fulfilled. Because x is 0 at this point the condition is true.
  • `System.out.print(” “); this will print a space
  • System.out.print("n"); this line in not in the brackets of the if-statement so it will also print.
  • if (x> 1 ) { x is 0 at this point so the condition is false and the program will skip everything in between these brackets
  • if ( x == 1 ) { this condition is also false because x is 0 so the program will skip everything in between these brackets
  • if ( x < 1 ) { this condition is true and `System.out.print(“oise”)“ prints “oise”
  • System.out.println(""); starts a new line
  • x = x + 1; the x variable is incremented by one: new x = 0 + 1 = 1

So the first iteration of the while statement yields:

a noise

For the second iteration of the while loop:

x is 1 and we follow the logic sequence again:

  • while ( x < 4 ) { this is true so we enter the brackets
  • System.out.print("a"); a is printed
  • if ( x < 1 ) { this statement is false, so next line is skipped
  • System.out.print("n"); n is printed
  • if ( x < 1 ) { this statement is false, so next line is skipped
  • if (x> 1 ) { this statement is false, so next two lines are skipped
  • if ( x == 1 ) { this is true
  • System.out.print("noys"); noys is printed
  • the next if-statement is also false
  • System.out.println(""); a new line is started
  • x = x + 1; and x is incremented

So the second iteration of the while-statement yields:

annoy

I think it is a good exercise now for you to try and figure out what happens in the next iteration of the while-loop.

solved How does this program work. Im rookie in programming so please explain it in simplified way