APCS: Unit 3

¡Supera tus tareas y exámenes ahora con Quizwiz!

What is the output from the following code? int[] nums = {-1, 1, -5, 5}; int count = 0; for (int n : nums) { if (n < 0) { n = -n; count++; } } for (int n : nums) System.out.print(n + " "); System.out.println(count);

-1 1 -5 5 2

What's an array reference?

-An array reference specifies the location of an array. -Copying the reference yields a second reference to the same array.

Indices (plural of index)

-In Java, an index is written within square brackets following array's name (for example, a[k]) -Indices start from 0; the first element of an array a is referred to as a[0] and the n-th element as a[n-1] -An index can have any int value from 0 to array's length - 1

Elements

-Individual locations are called array's elements. -When we say "element" we often mean the value stored in that element. -Rather than treating each element as a separate named variable, the whole array gets one name. -Specific array elements are referred to by using array's name and the element's number, called index or subscript.

Example of finding the maximum in an array w/o using "Math":

-The loop starts at 1 because we initialize largest with values[0]. double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } }

Why do we need arrays?

-The power of arrays comes from the fact that the value of an index can be computed and updated at run time. -Arrays give direct access to any element — no need to scan the array.

What is a "for-each" loop?

-Works both with standard arrays and ArrayLists -Convenient for traversing arrays (and Lists - Chapter 13) -Replaces iterators for collections -You can use the enhanced for loop to visit all elements of an array.

Limitations of a "for-each" loop?

-You cannot add or remove elements within a "for each" loop. -You cannot change elements of primitive data types or references to objects within a "for each" loop.

The expression Math.random() * 6 generates random numbers between

0 & 5.9999999999999999

By default, what is each number in an array?

0.0

What are the values of elements in arrays a and b after the following code is executed? int[] a = {1, 2, 3}; int[] b = a; b[2] = a[1]; a[1] = a[2];

1, 2, 2 and 1, 2, 2

Consider the following method: public void doSomething(int[] a) { a[2] = a[1]; a[3] = a[2]; } If a is declared as int[] a = {1, 2, 3, 4}; what are the values in a after doSomething(a) is called?

1, 2, 2, 2

Consider the following array: int[] a = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 0 }; What is the value of total after the following loops complete? int total = 0; for (int i = 1; i < 10; i = 2 * i) { total = total + a[i]; }

11

Consider the following array: int[] a = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 0 }; What is the value of total after the following loops complete? int total = 0; for (int i = 1; i < 10; i = i + 2) { total = total + a[i]; }

12

Consider the following array: int[] a = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 0 }; What is the value of total after the following loops complete? int total = 0; for (int i = 0; i < 10; i++) { total = total + a[i]; }

25

What is the output of the following segment of code? int[] array = {1, 19, 40, 6, 7}; int x = array[0]; for (int i = 0; i < array.length; i++) { if (array[i] > x) { x = array[i]; } } System.out.println(x); A) 40 B) 1 C) 7 D) 6

A

What is the output? int sum = 0; int[] quickMath = {2, 2, -1}; for (int i = 0; i < quickMath.length; i++) { sum += quickMath[i]; } System.out.println("That's " + sum + "! Quick Maths!"); A) That's 3! Quick Maths! B) That's 2! Quick Maths! C) 3 D) That's 4! Quick Maths!

A

Which of the following will return 100? int[] nums = {6, 10, 100, 4}; A) nums[2] B) nums[3] C) nums[0] D) None of the above

A

What would be the error if an index is negative or if it is greater than the length of the array - 1?

ArrayIndexOutOfBoundsException

Can you change the length of an array? A) Yes B) No C) Only if it is an array of primitive data types (e.g. ints)

B

Consider the following method, which is supposed to return the value of the largest element in an array of integers: // Precondition: a.length > 0 public int findMax(int[] a) { int max = a[0]; // Line 1 for (int i = 1; i <= a.length; i++) // Line 2 { if (a[0] > max) // Line 3 max = a[i]; // Line 4 } return max; // Line 5 } Unfortunately it has two bugs. On which lines? A.Line 1 and Line 2 B.Line 2 and Line 3 C.Line 2 and Line 4 D.Line 1 and Line 3

B

What does the following code print? int[] arr = { ... }; int maxNum = arr[0]; for (int i : arr) { if (maxNum > i) { maxNum = i; } } System.out.print(maxNum); A) The largest element in arr B) The smallest element in arr C) The first element in arr D) The last element in arr

B Don't be fooled by variable names! Don't worry, there aren't any similar tricks on the test

What will the following code print? int[] arr = {3, 0, 1, 4, 2}; for (int i : arr) { if (arr[i] % 2 == 0) { System.out.print(i + " "); } } A) 4 0 2 B) 3 1 4 C) 0 4 2 D) 3 1 2

B The for-each loop iterates through the actual elements of the array (3, 0, 1, 4, 2). However, the if statement checks if the value at that index is even (arr[3], arr[0], arr[1], arr[4], arr[2]). Because arr[3], arr[1], and arr[4] are even, the loop will print "3 1 4 ".

What is the correct format for initializing an array? A) int[3] nums; B) double{} values; C) String[] names; D) intArray nums;

C

What is the output of the following segment of code? int[] arr = {5, 8, 11, 16, 17}; for (int index = 6; index > arr.length; index--) { System.out.print(arr[index] + " "); } A) 0 0 0 0 0 B) 17 16 11 8 5 C) Index out of bounds error D) 5 8 11 16 17

C

Which of the following correctly refers to the last element in the array points? A.points[points.length] B. points[points.length()] C. points[points.length - 1] D. points[points.size() - 1]

C

Which of the following statements declares and initializes an array sample of 10 integers? A. int sample = new int[10]; B. int[] sample = new int(10); C. int[] sample = new int[10]; D. int[] sample = new sample(10);

C

What will the following code print? int[] arr = {1, 2, 3, 5, 6, 7, 8, 9, 10}; int negSum = 0; for (int i = 0; i < arr.length; i++) { negSum =- arr[i]; } System.out.print(negSum); A) -55 B) -51 C) -10 D) Error

C Because the code says "=-" and not "-=", the last iteration of the for loop will set negSum to -10. If the code did say "-=", the answer would be -51 (note the missing 4).

What is the output? int[] arr = new arr[10]; System.out.println(arr[10]) A) 0 B) null C) It will not compile D) Index out of bounds error

C The correct syntax is "new int[10]", not "new arr[10]"

Which of the following correctly constructs an array? A) int[] array = new array[]; B) int array[] = new array[]; C) int[] array = new int[10]; D) int array[] = new int[10];

C or D, although C is preferred

Consider the following line of code: int[] somearray = new int[15]; Which one of the following options is a valid line of code for displaying the eighth element of somearray? A. System.out.println(somearray[8]); B. System.out.println(somearray(8)); C. System.out.println(somearray(7)); D. System.out.println(somearray[7]);

D

What happens in the following code fragment? int[] fibo = {1, 1, 2, 3, 5}; System.out.println(fibo[-1]); A.Syntax error B. 0 is displayed C. An unpredictable number is displayed D. ArrayIndexOutOfBoundsException

D

What is wrong with the following code? int[] arr = { ... }; //Finds the largest element int maxElement = 0; for (int i : arr) { maxElement = Math.max(i, maxElement); } System.out.print(maxElement); A) It finds the smallest element instead B) It won't work if one of the elements is zero C) It won't work if some of the elements are negative D) It won't work if the largest element is negative

D Because maxElement is initialized as zero and not the first element of the array, this won't work if all the elements in the array are negative.

What is the difference between declaring and constructing arrays?

Declaring just says an array is possible, but constructing actually creates it

Which of the following correctly initializes an array arr to contain four elements each with value 0? I. int [] arr = {0,0,0,0}; II. int [] arr = new int [4]; III. int [] arr = new int [4]; for (int i = 0; i < arr.length; i++) arr[i] = 0; A. I only B. III only C. I and III only D. II and III only E. I, II, and III

E

Which of the following is the correct syntax to declare an array of ten integers? A. int a[10] = new int[10]; B. int[10] a = new int[10]; C. []int a = [10]int; D. int a[10]; E. int[] a = new int[10];

E

Once an array is constructed, can you change its length?

No, arrays have fixed length once constructed

1. True or false? (a)Once created, an array cannot be resized. (b)Java supports arrays with elements of any class type. (c)When an array of objects is created using the new operator, its elements get random values.

T (a)Once created, an array cannot be resized. T (b)Java supports arrays with elements of any class type. F (c)When an array of objects is created using the new operator, its elements get random values.

Given: String[] abc = {"A", "B", "C"}; which of the following loops will display ABC? (a)for (int i = 0; i < 3; i++) System.out.print(abc[i]); (b)for (String s : abc) System.out.print(s[0]); (c)for (String s : abc) System.out.print(s);

T (a)for (int i = 0; i < 3; i++) System.out.print(abc[i]); F (b)for (String s : abc) System.out.print(s[0]); T (c)for (String s : abc) System.out.print(s);

In the construction of an array, what does the number in brackets represent?

The number of elements in the array

What is the limitation to an array:

They have a fixed length

Array

a block of consecutive memory locations that hold values of the same data type.

What must an index of an array be?

at least zero and less than the size of the array (length - 1).

Rewrite (a) to make an array of 9 random numbers between 0 and 50.

double [] x = new double [9]; for (int i = 0; i < x.length; i++) { x [i] = (int) (Math.random() * 51); }

Compute and print the minimum value in x. Your program should find this value by examining each item in the array.

double smallest = x[0]; for (int i = 1; i < x.length; i++) { if (x[i] < smallest) { smallest = x[i]; } } System.out.println("Smallest: " + smallest);

Example of specifying the initial values when creating an array:

double[] moreValues = { 32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65 };

Example of initializing the array variable with the array:

double[] values = new double[10];

Example of declaring a variable:

double[] values;

Create an array x of doubles with an initializer list that contains the following values: 8, 4, 5, 21, 7, 9, 18, 2, and 100.

double[] x = {8, 4, 5, 21, 7, 9, 18, 2, 100}; double sum = 0;

Use an enhanced for loop to compute to print the total of all the elements in array x.

for (double value : x) { sum = sum + value; } System.out.println("Sum of x : " + sum);

Rewrite as a for-each loop: for (int i = 0; i < values.length; i++) { total = total + values[i]; }

for (double x : values) { total = total + x; }

Rewrite as a for loop: int i = 0; for (double x : values) { values[i] = 2 * x; i++; }

for (int i = 0; i < values.length; i++) { values[i] = 2 * values[i]; }

Example of filling an array:

for (int i = 0; i < values.length; i++) { values[i] = i * i; }

Rewrite as a for loop: public static int sum(int[] data) { int sum = 0; for (int n : data) { sum += n; } return sum; }

for (int i=0; i<data.length; i++) { sum = sum + data[i]; }

Rewrite as a for-each loop: for (int i = 0; i < temps.length; i++) { if (temps[i] > average) { above++; } }

for (int n : temps) { if (n > average) { above++; } }

An enhanced for loop is also known as a

for-each loop

Describe what an enhanced for loop does and what it's limitations are.

for-each loops are a simplified way to visit each element in the array. It cannot add or remove any elements and doesn't use an index variable.

We can use the Math.random method to generate random integers. You will use an array to test whether the random generator is fair; that is, whether each possible value is generated approximately the same number of times. Your program should ask the user: How many random numbers should be generated? What is the number of values for each random draw? (e.g., 6) Make an array with one element for each possible outcome. Set each element to 0. Then keep calling the random number generator. If it returns a value v, then increment the counter belonging to v.

import java.util.Scanner; public class RandomChecker { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("How many random numbers do you want to generate? "); int n = in.nextInt(); System.out.println("What is the number of values for each random draw? "); int max = in.nextInt(); int[] a = new int[max]; int i; // Generate the numbers and keep track of how many of each is generated for (i = 0; i < n; i++) { int x = (int) (Math.random() * max); a[x]++; } // Print the list of occurrences of each number for (i = 0; i < max; i++) { System.out.println(i + " " + a[i]); } } }

Example of inputting a random number:

int randomNum = (int) (Math.random () * 5)

Declare and initialize an array that holds the numbers 1, 3, 7, 11, 16, 23, 30 and write a method that randomly chooses and returns one of them.

private int[]numbers = {1, 3, 7, 11, 16, 23, 30}; public int randomChoice () { return numbers [(int) (Math.random() * numbers.length)]; }

Create a class called CustomerLister with a main method that instantiates an array of String objects called customerName. The array should have room for five String objects. Create an array with the following values: Cathy Ben Jorge Wanda Freddie Print the array of names using an enhanced for loop.

public class CustomerLister { public static void main(String[] args) { String[] customerName = {"Cathy", "Ben", "Jorge", "Wanda", "Freddie"}; for (String name: customerName) { System.out.println(name); } } }

Create a class called CustomerLister with a main method that instantiates an array of String objects called customerName. The array should have room for five String objects. Create an array with the following values: Cathy Ben Jorge Wanda Freddie Print the array of names using a standard for loop.

public class CustomerLister { public static void main(String[] args) { String[] customerName = {"Cathy", "Ben", "Jorge", "Wanda", "Freddie"}; for (int i = 0; i < customerName.length; i++) { System.out.println(customerName[i]); } } }

Example of finding the maximum in an array w/ using "Math":

public class MaxZS { public static void main (String[] args) { int[ ] numbers = {1,5,3,6,2,4}; int max = numbers[0]; for (int num: numbers) { max = Math.max(max, num); } System.out.print(max); } }


Conjuntos de estudio relacionados

USA Test Prep Benchmark Pre Test - NETOCEKALU K12

View Set

Middle East Countries and Capitals

View Set

Ch.16 - Integrated Marketing Communications (IMC)

View Set