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.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- 6.8 v10 vs 6.2 v8
- 6.2 ford vs 6.8 ford
- macmillan english 6 unit 6 wirksheet student key to correction
- macmillan english 6 unit 6 worksheet student key to correction
- 6 8 v10 vs 6 2 v8
- 6 2 ford vs 6 8 ford
- mark 6 1 6 commentary
- chapter 6 assessment answers economics
- 6 5 vs 6 8 ballistics chart
- 6 6 liters to cubic inches
- chapter 6 assessment answers biology
- dunkin donuts buy 6 get 6 free