87.3k views
2 votes
What will print out when the following code executes? int[] nums = {1, 2, 3, 4, 5, 6}; int count = 0; while (nums[count] % 2 != 0) nums[count+1] ++; count++; System.out.println(count); 0 0 1 02 03 05

User Christan
by
8.6k points

1 Answer

3 votes

Answer:

The code will result in an infinite loop because when count is initially set to 0, it will enter the while loop and continue to increment the next element in the array until it reaches the end of the array. However, if all the elements in the array are odd, then the loop will continue indefinitely since none of the elements will satisfy the condition nums[count] % 2 != 0 . The code will not print anything.

Here's an example of a corrected version of the code that counts the number of even integers in the nums array:

int[] nums = {1, 2, 3, 4, 5, 6};

int count = 0;

for (int i = 0; i < nums.length; i++) {

if (nums[i] % 2 == 0) {

count++;

}

}

System.out.println(count);

This code will output the value 3 , which is the number of even integers in the nums array.

Step-by-step explanation:

User Ecropolis
by
8.2k points

Related questions