40. Consider the program below: public class Test { public static void main(Stri
ID: 3724727 • Letter: 4
Question
40. Consider the program below:
public class Test
{
public static void main(String[] args)
{
Int[] a;
a = new int[10];
for(int i = 0; i < a.length; i++)
a[i] = i + 2;
int result = 0;
for(inti = 0; i < a.length; i++)
result += a[i];
System.out.printf(“Result is: %d%n”, result);
}
}
The output of this program is:
a. 62
b. 64
c. 65
d. 67
44. Assume array items contain the integer values 0, 2, 4, 6, and 8. Which of the following uses the enhanced for loop to display each value in array items?
a. for(int i = 0 : items.length)
System.out.printf("%dn%”, items[i]);
b. for(inti : items) System.out.printf(“%d%n”, i);
c. for(int i: items) System.out.printf(“%d%n”, items[i]);
d. for(int i = 0; i < items.length; i++)
System.out.printf("%dn%”, items[i]);
Explanation / Answer
40. Ans: c. Result is 65
In the program, we declare an integer array a, and allocate it a size of 10. Then to initialize it, for loop is used starting from i = 0 to array length i.e. 10 in which every ith element is assigned as i+2. So, the array looks like this: 2 3 4 5 6 7 8 9 10 11.
Then we declare another integer result initialized as 0. And using similar for loop as before, we update result by adding elements of array a to it in each iteration.
So, basically result will store the sum of all the array elements which is 65.
44. Ans: b. for(int i : items) System.out.printf(“%d%n”, i);
Here, the array contains 0, 2, 4, 6, 8. Then the for loop takes an integer i to traverse through the array items in such a way that in each iteration, the value of currently scanned element of array is copied to i and inside the for loop, we print the value of i, thus printing the array elements.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.