Name: ______Student ID:______

Tutorial 6

Question One

This is Question 6.1 on page 314 from the textbook. Which of the following are valid

declarations? Which will instantiate an array object? Explain your answers.

a. int primes = {2, 3, 4, 5, 7, 11}; //

b. float elapsedTimes[] = {11.47, 12.04, 11.72, 13.88}; //

c. int [] scores = int[30]; //

d. int[] primes = new {2, 3, 5, 7, 11}; //

e. int[] scores = new int[30]; //

f. char grades[] = {'a', 'b', 'c', 'd', 'f'}; //

g. char[] gardes = new char[]; //

Question Two

Answer the following questions regarding an array called fractions.

a)  Declare a constant variable ARRAY_SIZE initialized to 10.
b)  Declare an array with ARRAY_SIZE elements of type float and initialize the elements to 0.
c)  Name the forth element from the beginning of the array.
d)  Refer to array element 4.
e)  Assign the value 1.667 to array element 9.
f)  Assign the value 3.333 to the seventh element of the array.
g)  Sum all the elements of the array using a for loop.

Question Three

Write a small program to declare an array containing integers -3, 50, 1, -5, 7, -20,

0, 9, 100, and find and print to the screen the smallest and the largest numbers in the array.

Ouptut:

The Smallest Number is –20.

The Largest Number is 100.

public class SmallLarge

{

public static void main (String arg[])

{

}//end main

} //end class

Question Four

Write the program that outputs the following to the console window (i.e. the screen) for an array that contains 9 odd numbers and 12 even numbers:

The number of odd numbers in the array is 9

The number of even numbers in the array is 12

public class ArraySplit

{

public static void main (String args[])

{

int anArray[] = {23, 43, 65, 87, 24, 86, 98, 9, 12, 11, 32, 76,

42, 87, 88, 95, 10, 12, 44, 62, 83};

int oddCnt=0; //counts the odd numbers in the array

int evenCnt=0; //counts the even numbers in the array

System.out.println(“The number of odd numbers in the array is “ + oddCnt);

System.out.println(“The number of even numbers in the array is “ + evenCnt);

}//end main

}//end class

3