Solution

advertisement
Practice Array Problems (30 minutes)
1. Tracing Array Programs
Answer the questions below about each of the following bits of code.
a. What elements does the values array contain after the following statement?
double [] values = new double [5];
for (int i = 0; i < values.length;i++)
{
values[i] = i*i;
}
Answer: 0, 1, 4, 9, 16 but not 25
b. What does array a look like after the following code executes?
int [] a = {4, 1, -6, -2, 9, 3};
int aSize = a.length;
for (int i=0; i<aSize/2; i++)
{
int temp = a[i];
a[i] = a[aSize-i-1];
a[aSize-i-1] = temp;
}
Answer:
a = {3, 9, -2, -6, 1, 4}
(reverse order)
c. What does the following code display on the screen?
public class Test
{
public static void main(String[] args)
{
int [] list1 = {1, 2, 3};
int [] list2 = list1;
int [] list3 = new int[3];
for(int i=0; i<list2.length; i++) {
list1[i]++;
list3[i] = list2[i];
list3[i]++;
System.out.println(
list1[i] + " " + list2[i] + " " + list3[i]);
}
}
}
Answer:
2 2 3
3 3 4
4 4 5
2. Writing Java Code with Arrays
a. Write a Java statement to create an array to hold 10 double values.
Answer: double[] list = new double[10];
b. Assign value 5.5 to the last element in the array you just created.
Answer: list[list.length – 1] = 5.5;
c. Display the sum of the first two elements.
Answer: System.out.println(list[0] + list[1]);
d. Write a loop that computes the sum of all elements in the array.
Answer:
double sum = 0;
for (int i = 0; i < list.length; i++)
sum += list[i];
e. Write a loop to find the alternating sum of all elements in array a. The alternating sum adds
even-index elements, and subtracts odd-position elements. For instance, if a contains {1, 2, 3, 4,
5}, the alternating sum would be 1 – 2 + 3 – 4 + 5 = 3
Answer:
double altSum = 0;
for(int i=0; i<a.length; i++) {
if(i % 2 == 0) { // even index: add to sum
altSum = altSum + a[i];
}
else { // odd index: subtract from sum
altSum = altSum – a[i];
}
}
f.
Write a complete Java program that reads 20 values of type double from the keyboard into an
array. Then:
- Display the last (20th) number read.
- Display the difference between each number in the array and the last number in the array.
For example, if the array contains {7, 9, -2, 5}, the program should display
2 (because 7-5=2)
4 (because 9-5=4)
-7 (because -2-5=-7)
0 (because 5-5=0)
Answer:
import java.util.Scanner;
public class DiffFromLast
{
public static void main(String [] args)
{
Scanner kb = new Scanner(System.in);
double [] vals = new double[20];
for(int i=0; i<vals.length; i++)
{
vals[i] = kb.nextDouble();
}
System.out.println("last number = " + vals[vals.length-1]);
for(int i=0; i<vals.length; i++) {
System.out.println(vals[i] – vals[vals.length-1]);
}
}
}
Download