Consider the following code segment and answer the questions below. Doing questi
ID: 3855607 • Letter: C
Question
Consider the following code segment and answer the questions below. Doing question 9 first might help you with questions 6 - 8 if you are stuck. int i: int j: int[] arr = {6, 4, 7, 2, 1}: for (i = arr.length - 1: i > 1: i-) { System.out.println("Hello World!"): j = arr[i]: } 6. How many times will the above code print the sentence "Hello World!"? 7. What is the value of the integer variable i after executing the for loop? 8. What is the value of the integer variable j after executing the for loop? 9. Convert the for loop above to a while loop. You need to ensure that your code prints the sentence "Hello World!" the same number of times and ends with the same value for the integer value for the variables i and j. int i: int j: int[] arr = {6, 4, 7, 2, 1};Explanation / Answer
6.
3 times .
arr.length = 5
arr.length-1 = 4
for(i=arr.length-1;i>1;i--) , i = 4,3,2, for 3 values of i, Hello World! will be printed.
7. i = 1
i will be decremented from 4 to 1 and since 1 does not satisfy for loop condition so the loop ends.
8.
j = 7
j is assigned 3 values for 3 values of i
j = arr[4] = 1
j = arr[3] = 2
j = arr[2] = 7
and 7 is the last value
9.
class Test
{
public static void main (String[] args)
{
int i,j;
j= 0;
int[] arr = {6,4,7,2,1};
i=arr.length-1; // initialization
while(i>1) //condition
{
System.out.println("Hello world");
j = arr[i];
System.out.println(j);
i--; //decrementation
}
}
}
Output:
Hello world
1
Hello world
2
Hello world
7
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.