Tutorial 6 - Answers



Tutorial 6 – Answers

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}; // [] missing

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

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

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

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

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

g. char[] gardes = new char[]; // quantifier in [] missing

Question Two.

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.

The output should be:

The Smallest Number is –20.

The Largest Number is 100.

public class SmallLarge

{

public static void main (String arg[])

{

int numbers[] = {-3, 50, 1, -5, 7, -20, 0, 9, 100};

int min=0, max=0;

for (int i = 0; i < numbers.length; i++) {

if (numbers[i] < min)

min = numbers[i];

if (numbers[i] > max)

max = numbers[i];

}

System.out.println ("The Smallest Number is " + min);

System.out.println ("The Largest Number is " + max);

}//end main

} //end class

Question Three

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

int i;

//go through each element in the array and determine if odd or even and increase

//oddCnt or evenCnt as appropriate.

for (i = 0; i ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download