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 bracketsif ( x == 1 ) {
this condition is also false because x is 0 so the program will skip everything in between these bracketsif ( x < 1 ) {
this condition is true and `System.out.print(“oise”)“ prints “oise”System.out.println("");
starts a new linex = 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 bracketsSystem.out.print("a");
a is printedif ( x < 1 ) {
this statement is false, so next line is skippedSystem.out.print("n");
n is printedif ( x < 1 ) {
this statement is false, so next line is skippedif (x> 1 ) {
this statement is false, so next two lines are skippedif ( x == 1 ) {
this is trueSystem.out.print("noys");
noys is printed- the next if-statement is also false
System.out.println("");
a new line is startedx = 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