184k views
6 votes
Consider the following code segment. int[][] arr = {{3, 2, 1}, {4, 3, 5}}; for (int row = 0; row < arr.length; row++) { for (int col = 0; col < arr[row].length; col++) { if (col > 0) { if (arr[row][col] >= arr[row][col - 1]) { System.out.println("Condition one"); } } if (arr[row][col] % 2 == 0) { System.out.println("Condition two"); } } } As a result of executing the code segment, how many times are "Condition one" and "Condition two" printed?

User Ncubica
by
7.8k points

1 Answer

5 votes

Answer:

Condition one - 1 time

Condition two - 2 times

Step-by-step explanation:

Given

The above code segment

Required

Determine the number of times each print statement is executed

For condition one:

The if condition required to print the statement is: if (arr[row][col] >= arr[row][col - 1])

For the given data array, this condition is true only once, when


row = 1 and
col = 2

i.e.

if(arr[row][col] >= arr[row][col - 1])

=> arr[1][2] >= arr[1][2 - 1]

=> arr[1][2] >= arr[1][1]

=> 5 >= 3 ---- True

The statement is false for other elements of the array

Hence, Condition one is printed once

For condition two:

The if condition required to print the statement is: if (arr[row][col] % 2 == 0)

The condition checks if the array element is divisible by 2.

For the given data array, this condition is true only two times, when


row = 0 and
col = 1


row = 1 and
col = 0

i.e.

if (arr[row][col] % 2 == 0)

When
row = 0 and
col = 1

=>arr[0][1] % 2 == 0

=>2 % 2 == 0 --- True

When
row = 1 and
col = 0

=>arr[1][0] % 2 == 0

=> 4 % 2 == 0 --- True

The statement is false for other elements of the array

Hence, Condition two is printed twice

User Eduardo Reveles
by
8.3k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.