23. (6 marks) Consider the following array: int[] a = { 1, 2, 3, 0, 3, 2, 1 }; (
ID: 3573375 • Letter: 2
Question
23. (6 marks) Consider the following array: int[] a = { 1, 2, 3, 0, 3, 2, 1 };
(1 mark each) What is the value stored in the variable total when the followings loops complete?
a) int total = 0;
for(int i = 0; i<7; i++)
{ total = total + a[i]; }
b) int total = 0;
for(int i = 0; i<5; i+=3)
{ total = total + a[i]; }
(2 marks each) Again, consider the array above. What are the contents of array a after the following loops complete?
c) for(int i = 6; i>1; i--)
{ a[i] = a[i] * 2; }
d) for(int i = 0; i < 7; i++)
{ a[i] = 5; }
24. (2 marks) Write the statements required to create and initialize the 2D array:
(2 marks) Write the statements required to swap the top-right element with the bottom-left element of the 2D
array above. You may hard-code the indexes here.
25. (6 marks) Write a method that takes a 2D array of integers as an argument. The array returns a new 2D array
of integers of the same size (same number of rows and columns). The values in the returned array are the same
as those in the argument array EXCEPT that any negative values are made positive. The header for the method is
given below:
public static int[][] absoluteArray2D(int[][] in){
Explanation / Answer
a)
i a[i] total total = total+a[i]
0 1 0 0+1 = 1
1 2 1 1+2 = 3
2 3 3 3+3 = 6
3 0 6 0+6 = 6
4 3 6 6+3 = 9
5 2 9 9+2 = 11
6 1 11 11+1 = 12
total = 12
b)
i a[i] total total = total+a[i]
0 1 0 0+1 = 1
3 0 1 1+0 = 1
total = 1
c)
i a[i] a[i] = a[i]*2
6 1 1*2 = 2
5 2 2*2 = 4
4 3 3*2 = 6
3 0 0*2 = 0
2 3 3*2 = 6
a = {1,2,6,0,6,4,2}
d)
i a[i] = 5
0 5
1 5
2 5
3 5
4 5
5 5
6 5
a = {5,5,5,5,5,5,5}
24)
2D Array Initialize and Decleration :
int rows = 3;
int cols = 3;
int TwoArray[rows][cols];
// Using Loops
int i,j;
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++) {
TwoArray[i][j] = 3 ;
}
}
// Initialization while declaration
int TwoArray[3][3] = {{1,2,3},{4,5,6},{7,8,9}}
// swap the top-right element with the bottom-left element
// top-right element position : [0][cols-1]
// bottom-left element position : [rows-1][0]
int temp = TwoArray[0][cols-1];
TwoArray[0][cols-1] = TwoArray[rows-1][0];
TwoArray[rows-1][0] = temp;
25)
public static int[][] absoluteArray2D(int[rows][cols] in) {
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
if(in[i][j] < 0) {
in[i][j] = (-1) * (in[i][j]);
}
}
}
return in;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.