Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

How many times will the print statement execute in the following code? Answer is

ID: 3580023 • Letter: H

Question

How many times will the print statement execute in the following code? Answer is 6, but i dont understand how. The first condition would carry out 4 times untill it got to the array length. But, i am lost on the second condition. If y = 0 and x would be 0 on the in the begining wouldnt 0 < 0 be false and the next one would be y = 1 and x = 1 which would be false too.

int[] myArray = new int[4];
for (int x = 0; x < myArray.length; x++) {

for (int y = 0; y < x; y++) { System.out.println( myArray[x] );

} }

Explanation / Answer

int[] myArray = new int[4];
for (int x = 0; x < myArray.length; x++)
{ // a)
for (int y = 0; y < x; y++)
{ // b)
System.out.println( myArray[x] );
}
}

1) The control enters the outer for loop it assigns the value 0 to x and the logical expression x < myArray.length ( 0 < 4) is evaluated.
The logical expression results true so the control enters at the left brace ( point // a)
2) The control enters the inner for loop it assigns the value 0 to y and the logical expression y < x ( 0 < 0) is evaluated.
The logical expression results false so the control comes out of the inner for loop
3) Now the control goes to x++ and x value is incremented by 1.
and the logical expression x < myArray.length ( 1 < 4) is evaluated.
4) The control enters the inner for loop it assigns the value 0 to y and the logical expression y < x ( 0 < 1) is evaluated.
The logical expression results true so the control enters the left brace ( point //b)
5) So the statements are executed with in the braces. There is only one statement System.out.println( myArray[x] );
So that is executed.
6) After executing the statement right brace is there
so the control goes to y++ and y is incremented by 1.
Then and the logical expression y < x ( 1 < 1) is evaluated.
It results false. So the control comes out of the loop.
7) From step 3 it is followed.


X Value

Y Value

Result

0

0

Not executed

1

0

Executed

1

1

Not executed

2

0

Executed

2

1

Executed

2

2

Not Executed

3

0

Executed

3

1

Executed

3

2

Executed

3

3

Not Executed

4

Comes out of the loop

Program ends

Description

X Value

Y Value

Result

0

0

Not executed

1

0

Executed

1

1

Not executed

2

0

Executed

2

1

Executed

2

2

Not Executed

3

0

Executed

3

1

Executed

3

2

Executed

3

3

Not Executed

4

Comes out of the loop

Program ends

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote