comp sci test 5 (arrays)

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

public void changeIt(int[] arr, int index, int newValue) { arr[index] += newValue; } Which of the following code segments, if located in a method in the same class as changeIt, will cause the array myArray to contain {0, 5, 0, 0} ?

int[] myArray = new int[4]; changeIt(myArray, 1, 5);

int[] arr = {1, 2, 4, 0, 3}; for (int i : arr) { System.out.print(i); } Which of the following code segments will produce the same output as the code segment above?

III only

public static String changeStr(String str) { String result = ""; for (int i = str.length() - 1; i >= str.length() / 2; i -= 2) { result += str.substring(i, i + 1); } return result; } What value is returned as a result of the method call changeStr("12345") ?

"53"

How do you initialize an array called arr of 5 ints with default values?

int[] arr = new int[5];

for (int i = 2; i < 9; i++){ System.out.print(i + ", ");}

2, 3, 4, 5, 6, 7, 8,

int[] scores = {80, 92, 91, 68, 88}; for(int i = 0; i < scores.length; i++) { System.out.println(scores[i] - 1); }

79 91 90 67 87

How often is the inner loop of a nested loop run?

Each time the outer loop runs

int[] scores = {80, 92, 91, 68, 88}; for(int score : scores) { System.out.println(score); }

80 92 91 68 88

int r = 0; int sum = 0; /* missing loop header */ { if (r % 2 == 1) { sum += r; } r++; } System.out.println(sum); Which of the following could replace /* missing loop header */ to ensure that the code segment will work as intended?

while (r <= 101)

public void processString (String str){ str = str.substring(2, 3) + str.substring(1, 2) + str.substring(0, 1);} What is printed as result of executing the following statements (in a method in the same class)?String str = "Frog";processString(str);System.out.println(str);

Frog

int[] scores = {80, 92, 91, 68, 88}; for (int i = 0; i < scores.length; i += 2) { System.out.println(scores[i] = scores[i] * 2); }

160 182 176

int[] arr = {1, 2, 3, 4, 5};int[] copy = arr;copy[4] = 2; After this code runs, what is the value of arr[4]?

2

public int getTheResult(int n) { int product = 1; for (int number = 1; number < n; number++) { if (number % 2 == 0) product *= number; } return product; } What value is returned as a result of the call getTheResult(8) ?

48

Which of the following will initialize a boolean array of three elements all containing true? I. boolean[] arr = {true, true, true}; II. boolean[] arr = new boolean[3]; III. boolean[] arr = new boolean[3];for (int i = 0; i < arr.length; i ++){ arr[i] = true;}

I and III

Which of the following can be used to replace /* missing code */ so that isDecreasing will work as intended?

II only

Which of the following is the best postcondition for checkArray ?

Returns the index of the largest value in array array

public class SayHello{ public void run() { String stringArray[] = {"h", "e", "l", "l", "o", "w"}; for(int i=0; i <= stringArray.length; i++) { System.out.print(stringArray[i]); } }}

error

True or False: You can modify the elements of an array when you traverse it with a for-each loop.

False

When would you use a for-each loop instead of a for loop?

If you want to access every element of an array and want to refer to elements through a variable name instead of an array index.

1: public void shiftRight(int[] arr)2: {3: int lastNum = arr[arr.length - 1];4: 5: for (int i = arr.length - 1; i > 0; i--)6: {7: arr[i] = arr[i - 1];8: }9: arr[0] = lastNum;10: }

The code will work as intended.

Which of the following statements is valid? Assume that variable arr is an array of i integers and that the following is true: arr[0] != arr[i] for all values from 1 through i - 1

The element arr[0] does not occur anywhere else in the array

public boolean twoInARow(int[] arr) { /* missing loop header */ { if (arr[k] == arr[k + 1]) { return true; } } return false; } Which of the following can be used to replace /* missing loop header */ so that the method will work as intended?

for (int k = 0; k < arr.length - 1; k++)

int[ ] values = {150, 34, 320, 2, 11, 100}; for (int i=0; i < values.length; i++) { if (values[i] % 10 == 0) System.out.println(values[i] + " is divisible by 10"); } which for-each loop would produce the same output?

for (int value : values) { if (value % 10 == 0) System.out.println(value + " is divisible by 10"); }

Which for loop will properly print "hello" 10 times?

for(int i = 0; i < 10; i++){ System.out.println("hello");}

public static int[] reverse(int[] arr) { int[] newArr = new int[arr.length]; for (int k = 0; k < arr.length; k++) { /* missing statement */ } return newArr; } Which of the following statements can be used to replace /* missing statement */ so that the method works as intended?

newArray[k] = arr[arr.length - k - 1];

How many stars are output when the following code is executed?for (int i = 0; i < 5; i++){ for (int j = 0; j < 10; j++) { System.out.println("*"); } }

50 stars

for (int c = 0; c < arr1.length; c++) { if (arr1[c] < minArray[c]) { arr1[c] = minArray[c]; } else { minArray[c] = arr1[c]; } } Which of the following changes will ensure that the code segment always works as intended?

Removing lines 5-8

public static void printAllCharacters(String str) { for (int x = 0; x < str.length(); x++) // Line 3 { System.out.print(str.substring(x, x + 1)); } } The following statement is found in the same class as the printAllCharacters method. printAllCharacters("ABCDEFG"); Which choice best describes the difference, if any, in the behavior of this statement that will result from changing x < str.length() to x <= str.length() in line 3 of the method?

The method call, which worked correctly before the change, will now cause a run-time error because it attempts to access a character at index 7 in a string whose last element is at index 6.

Why do we use while loops in Java?

To repeat some code while a condition is true

How many times will the following code print out the value of x?public static void main(String[] args){ int x = 1; while (x > 10) { System.out.println(x); x--; }}

0 times

What value will be held in mysteryNumber when this code finishes running? int mysteryNumber = 0;String[] mysteryArray = {"Finn", "Jake", "Bubblegum"};for(int i = 0; i < mysteryArray.length; i++){ mysteryNumber += mysteryArray[i].length();}

16

public boolean search(int[] arr, int target){ for (int number : arr) { if (number != target) { return false; } } return true;} Which of the following statements is true?

The code will not work correctly because the method may return false too soon.

String[] languages = {"Java", "JavaScript", "Python", "C++"}; Which of the following will produce an ArrayIndexOutOfBoundsException?

for (int i = 0; i <= languages.length - 1; i++){ System.out.println(languages[i]);}

int count = 0; for (int x = 1; x <= 3; x++) { /* missing loop header */ { count++; } } System.out.println(count); Which of the following should be used to replace /* missing loop header */ so that the code segment will print 6 as the value of count ?

for (int y = 0; y < x; y++)

int num = 1; while (num < 5) { System.out.println("A"); num += 2; } What is printed as a result of executing the code segment?

AA

for (int j = 1; j < 10; j += 2) { System.out.print(j); } Which of the following code segments will produce the same output as the code segment above?

int j = 1; while (j < 10) { System.out.print(j); j += 2; }

int[] scores = {80, 92, 91, 68, 88}; int index = 0; int mystery = 91; while (index < scores.length) { if (scores[index] == mystery) break; index ++; } System.out.println(index);

2

Which of the following arrays has a length of 5?

All of these

Which of the following can be used to replace /* missing loop header */ so that the code segment works as intended? for (int j = 0; j < 3; j++) for (int j = 1; j < 3; j++) for (int j = 1; j <= 3; j++)

I and III

public static int findMin (int[] arr){ int min = /* some value */; int index = 0; while (index < arr.length) { if (arr[index] < min) { min = arr[index]; } index++; } return min;} Which replacement(s) for /* some value */ will always result in correct execution of findMin?

I and III only

int WIDTH = 3;int HEIGHT = 3;String[] gameBoard = new String[WIDTH * HEIGHT];for(int m = 0; m < HEIGHT; m++){ for(int n = 0; n < WIDTH; n++) { int someNumber = m * WIDTH + n; if(someNumber % 3 == 0) { gameBoard[someNumber] = "X"; } else { gameBoard[someNumber] = "O"; } }}

["X", "O", "O", "X", "O", "O", "X", "O", "O"]

Which of the following are valid arrays? I. int[] coolArray = {1, 2, 3};II. int[] threeThings = {1.0, 2.0, 3.0};III. int[] = {"1", "2", "3"};

I and II

Why is having efficient algorithms important? I. It reduces the cost of running a program.II. It can improve the speed that programs operate.III. It increases the speed of innovations.

I and II

The following codes are intended to add 5 to each item in the array

I will correctly add 5 to the numbers array. II will not correctly add 5 to the numbers array

Which of the following initializes an array of 4 doubles called temperatures with the following initial values: 80.2, 65.3, 12.17, 20.21?

double[] temperatures = {80.2, 65.3, 12.17, 20.21};

// x has been initialized with a positive int valueint count = 0;while (count < x){ count++;}

x times

String[] fruit = {"Apple", "Pear", "Pineapple", "Carrot", "Banana", "Lettuce"}; Which code will correctly replace Carrot and Lettuce in the array?

fruit[3] = "Grape"; fruit[5] = "Blueberry";

Which of the following will execute without throwing an exception error? I. String str1 = "Golden"; String str2 = "Retriever"; if (str1.equals(str2)) { System.out.println("Golden Retriever!"); }II. String str1 = "Golden"; String str2 = str1.substring(4);System.out.println(str1 + str2);

Both I and II

public int countTarget(int[] arr, int target) { int count = 0; for (int j = 0; j <= arr.length; j++) // line 4 { if (arr[j] == target) { count++; } } return count; } Which of the following changes, if any, can be made to line 4 so that the method will work as intended?

Changing j <= arr.length; to j < arr.length;

Which statement could be added in place of /*missing code*/ in the while loop below so that it doesn't run indefinitely?public static void main(String[] args){ int x = 7; while (x > 0) { System.out.println(x);/* missing code */ }}

I and II

public static String mystery(String str1, String str2){ int index = str1.indexOf(str2); return str1.substring(index, index + str2.length());}What is true about mystery?I. It may return a string that is equal to str2. II. It may return a string that has no characters in common with str2. III. It may return a string that is equal to str1.

I and III

Which of the following are needed to correct the code? I. Change line 3 to: int i = 0; II. Change line 4 to: while (i < nums.length - 1) III. Swap lines 7 and 10

Make both I and II changes

int count = 0; for (int k = 0; k < 10; k++) { count++; } System.out.println(count); Which of the following code segments will produce the same output as the code segment above?

int count = 0; for (int k = 9; k >= 0; k--) { count++; } System.out.println(count);

int[] arr = {10, 5, 1, 20, 6, 25}; int sum = 0; for (int k = 0; k <= arr.length; k++) { sum += arr[k]; } System.out.println("The sum is " + sum); A runtime error occurs when the code segment is executed. Which of the following changes should be made so that the code segment works as intended?

The for loop header should be replaced with for (int k = 0; k < arr.length; k++).

Which of the following loops will NOT print every element in an integer array?

for (int i = 1; i < array.length; i++){ System.out.println(array[i-1]);}

How many times does the following loop execute?// x has been initialized with a positive int value greater than 5int count = 5;while (count < x){ count++;}

x - 5 times

boolean[] oldVals = {true, false, true, true}; boolean[] newVals = new boolean[4]; for (int j = oldVals.length - 1; j >= 0; j--) { newVals[j] = !(oldVals[j]); } What, if anything, will be the contents of newVals as a result of executing the code segment?

{false, true, false, false}

while(true){ System.out.println("Hello");}

Print Hello in an infinite loop

int[] scores = {80, 92, 91, 68, 88}; int sum = 0; for (int i = 0; i < scores.length; i++){ sum += scores[i]; } System.out.println((double) sum / scores.length);

Prints the average of the array

int[] numbers = {1, 2, 3, 4, 5}; int[] temp = new int[numbers.length]; for (int i = 0; i < numbers.length - 1; i++) { temp[i + 1] = numbers[i]; } temp[0] = numbers[numbers.length - 1]; numbers = temp; for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); }

5 1 2 3 4

Which of the following best describes the problem with the given implementation of the shuffle method?

The last element of the returned array (result [result.length − 1] ) may not have the correct value.

for (int x = 0; x <= 4; x++) // Line 1 { for (int y = 0; y < 4; y++) // Line 3 { System.out.print("a"); } System.out.println(); } Which of the following best explains the effect of simultaneously changing x <= 4 to x < 4 in line 1 and y < 4 to y <= 4 in line 3 ?

"a" will be printed the same number of times because while the number of output lines will decrease by 1, the length of each line will increase by 1.

for (int i = 0; i < n; i += 2){ if (/* condition to test */) { /* perform some action */ }}In terms of n, which Java expression represents the maximum number of times that/* perform some action */ could be executed?

(n + 1) / 2

for (int i = 1; i < 6; i++){ for (int y = 1; y <= 4; y++) { System.out.print("*"); } System.out.println();}

A rectangle of 5 rows with 4 stars per row.

What is the output after this code snippet runs? int[] scores = {80, 92, 91, 68, 88}; for(int i = 0; i < scores.length; i--) { System.out.println(scores[i]); }

ArrayIndexOutOfBoundsException

Which of the following changes should be made so that method findLongest will work as intended?

Insert the statement lenCount = 0; between lines 12 and 13.

int shortest = /* missing value */; for (String word : wordArray) { if (word.length() < shortest) { shortest = word.length(); } } System.out.println(shortest); Which of the following should be used as the initial value assigned to shortest so that the code segment works as intended?

Integer.MAX_VALUE

The method findLongest does not work as intended. Which of the following best describes the value returned by a call to findLongest ?

It is the number of occurrences of the value target in nums.

int[] highTemp = {88, 92, 94, 90, 88, 83};int target = 90;int count = 0; for (int temp : highTemp){ if (highTemp >= target) { count ++; }}System.out.println(count);

It will count the number of times the value in the highTemp array exceeds the target value.

public static double findAvg(double[] values) { double sum = 0.0; for (double val : values) { sum += val; } return sum / values.length; } Which of the following preconditions, if any, must be true about the array values so that the method works as intended?

No precondition is necessary; the method will always work as intended.

public static void addOneToEverything(int[] numbers) { for (int j = 0; j < numbers.length; j++) { numbers[j]++; } } Which of the following code segments, if any, can be used to replace the body of the method so that numbers will contain the same values?

None of the code segments will return an equivalent result.

public static String longestWord(String[] words) { /* missing declaration and initialization */ for (int k = 1; k < words.length; k++) { if (words[k].length() > longest.length()) { longest = words[k]; } } return longest; } Which of the following can replace /* missing declaration and initialization */ so that the method will work as intended?

String longest = words[0];

int j = 1; while (j < 5) { int k = 1; while (k < 5) { System.out.println(k); k++; } j++; } Which of the following best explains the effect, if any, of changing the first line of code to int j = 0; ?

There will be four more values printed because the outer loop will iterate one additional time.

for (int k = 1; k <= 7; k += 2) { System.out.print(k); } Which of the following code segments will produce the same output as the code segment above?

for (int k = 1; k <= 8; k += 2) { System.out.print(k); }

Which of the following code snippet gets the THIRD element in the scores array and assigns it to an int called myScore , then sets the FOURTH element in the scores array (previously declared) to 72?

int myScore = scores[2]; scores[3] = 72;

int val = 1; while (val <= 6) { for (int k = 0; k <= 2; k++) { System.out.println("Surprise!"); } val++; } How many times is the string "Surprise!" printed as a result of executing the code segment?

18

Given the following values of arr and the mystery method, what will the values of arr be after you execute: mystery()? private int[ ] arr = {-17, -14, 3, 9, 21, 34}; public void mystery(){ for (int i = 0; i < arr.length / 2; i += 2) { arr[i] = arr[i] * 2; }}

{-34, -14, 6, 9, 21, 34}

I. int[] numbers = {1, 2, 3, 4};for (int i = 0; i < numbers.length; i++){ numbers[i] += 5;} II. int[] numbers = {1, 2, 3, 4};for (int number : numbers){ number += 5;}

I will correctly add 5 to the numbers array. II will not correctly add 5 to the numbers array.

Assume that doSome is called and executes without error. Which of the following are possible combinations for the value of lim, the number of times Statement S is executed, and the number of times Statement T is executed?

II only

You are working at the frozen yogurt shop in the mall. Your boss asks you to count how many flavors have the word chocolate in their name. You begin going through the list of flavors, but quickly realize that their are over 9000 flavors to check! Luckily, your boss stored all of the different flavors in a Java Array named flavorArray on the company computer. Write a Java program to count the number of flavors that have chocolate in their name.

int chocolateFlavorCount = 0; for(int i = 0; i < flavorArray.length; i++){ if(flavorArray[i].contains("chocolate")) { chocolateFlavorCount++; } } System.out.println(chocolateFlavorCount);

for (int outer = 0; outer < 3; outer++) { for (/* missing loop header */) { System.out.print(outer + "" + inner + "_"); } } Which of the following can be used as a replacement for /* missing loop header */ so that the code segment produces the output 00_01_02_11_12_22_ ?

int inner = outer; inner < 3; inner++

int sum = 0; for (int n : arr) { sum = sum + 2 * n; } System.out.print(sum); Which of the following code segments will produce the same output as the code segment above?

int sum = 0; for (int k = 0; k < arr.length; k++) { sum = sum + 2 * arr[k]; } System.out.print(sum);

public static getValue(int[] data, int j, int k) { return data[j] + data[k]; } Which of the following code segments, when appearing in another method in the same class as getValue, will print the value 70 ?

int[] arr = {50, 40, 30, 20, 10}; System.out.println(getValue(arr, 1, 2));

public int[] addNum(int[] array, int first, int second, int num) { int[] newArray = new int[array.length]; newArray[first] = array[first] + num; newArray[second] = array[second] + num; return newArray; } Which of the following code segments, appearing in the same class as the addNum method, will result in array2 having the contents {0, 0, 13, 0, 9, 0, 0} ?

int[] array1 = {5, 2, 8, 6, 4, 3, 9}; int[] array2 = addNum(array1, 2, 4, 5);

int[] scores = {80, 92, 91, 68, 88}; int i = 0; while (i < scores.length - 1) { System.out.println(scores[i] * 2); i ++; }

160 184 182 136

int count = 5; while (count < 100) { count = count * 2; } count = count + 1; What will be the value of count as a result of executing the code segment?

161

What is printed as a result of executing the following code snippet?for (int k = 0; k < 25; k = k + 2){ if (k % 3 == 0) { System.out.print(k + " "); }}

0 6 12 18 24

int num = 1; int count = 0; while (num <= 10) { if (num % 2 == 0 && num % 3 == 0) { count++; } num++; } What value is stored in the variable count as a result of executing the code segment?

1

What does the following code snippet check for? int[] numbers = {1, 2, 3, 3, 4, 5}; boolean mysteryBoolean = false; for (int i = 0; i < numbers.length - 1; i++) { for (int j = i + 1; j < numbers.length; j++) { if (numbers[i] == numbers[j]) { mysteryBoolean = true; } } }

Finds duplicate values in an array

Consider the following code snippet. Is count < 5 always true, always false, or sometimes true/sometimes false at point 2?int count = 0;while (count < 5){ System.out.println("CodeHS Rocks!"); count++; // point 2}

count < 5 is sometimes true/sometimes false at point 2

public int numDigits(int num) { int count = 0; while (/* missing condition */) { count++; num = count / 10; } return count; } Which of the following can be used to replace /* missing condition */ so that the method will work as intended?

num != 0

String str = "RETRIEVER"; int index = str.substring(1, 4).indexOf("R"); what is the value of index?

2

String[] grades = {"A","C","B","A","B", "A"}; int mystery = 0; for (int i = 0; i < grades.length; i++) { if (grades[i].equals("A")) { mystery ++; } } System.out.println(mystery);

3

int[] arr = {3, 1, 0, 4, 2}; for(int j = 0; j < arr.length; j++) { System.out.print(arr[j] + j + " "); } What, if anything, is printed as a result of executing the code segment?

3 2 2 7 6

int[ ] values = {17, 34, 56, 2, 19, 100}; for (int value : values) { if (value % 2 == 0) System.out.println(value + " is even"); }

34 is even 56 is even 2 is even 100 is even

String str = "a black cat sat on a table"; int counter = 0; for (int i = 0; i < str.length() - 1; i++) { if (str.substring(i, i + 1).equals("a") && !str.substring(i + 1, i + 2).equals("b")) { counter++; } } System.out.println(counter); What is printed as a result of executing this code segment?

5

int outerMax = 10; int innerMax = 5; for (int outer = 0; outer < outerMax; outer++) { for (int inner = 0; inner <= innerMax; inner++) { System.out.println(outer + inner); } } How many values will be printed when the code segment is executed?

60

int[] scores = {80, 92, 91, 68, 88}; int myIndex = 0; for (int i = 1; i < scores.length; i++) { if (scores[i] < scores[myIndex]) { myIndex = i; } } System.out.println(scores[myIndex]);

68

what code segment will prduce this output? 1 1 1 1 1 2 2 2 2 3 3 3 4 4 5

for(int j = 0; j <= 5; j++) { for(int k = 5; k >= j; k--) { System.out.println(j + " "); } System.out.println(); }

public static int diff(int[] pred, int[] act) { int num = Integer.MIN_VALUE; for (int i = 0; i < pred.length; i++) { /* missing code */ } return num; } Which of the following code segments can be used to replace /* missing code */ so that diff will work as intended?

if (Math.abs(pred[i] - act[i]) > num) { num = Math.abs(pred[i] - act[i]); }


Ensembles d'études connexes

"American History" Herring {13.2} Video Lesson: Urban America: Urbanization

View Set

Lab 3.4 Interpreting Pedigree Diagrams

View Set

Patrick Henry's Speech Questions

View Set

Principles/Logical Fallacies Questions

View Set