CS - Chapter 6

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

To check whether a specific method is doing is job correctly, you can use the debugger tool called

"step into."

Which of the following loops executes the statements inside the loop before checking the condition?

do

Which code snippet produces the sum of the first n even numbers?

int sum = 0; for (int i = 1; i <= n; i++) { sum = sum + i * 2; }

A loop inside another loop is called a

nested loop.

Which of the following conditions can be added to the code below so it will loop until the user enters "no" or "NO"? Scanner in = new Scanner (System.in); System.out.print("Continue? "); String response = in.next(); while (/* put condition here */) { System.out.println("Hello beautiful!"); System.out.print("Continue? "); response = in.next(); }

!(response.equals("no") || response.equals("NO"))

What is the sentinel value in the following code snippet? public static void main(String[] args) { int age = 0; int sumOfAges = 0; int stop = 1; Scanner reader = new Scanner(System.in); System.out.println("Enter an age (-1 to stop): "); age = reader.nextInt(); while (age != -1) { sumOfAges = sumOfAges + age; System.out.println("Enter an age (-1 to stop): "); age = reader.nextInt(); } System.out.println("Sum of ages " + sumOfAges); return 0; }

-1

For which input values will the following loop not correctly compute the maximum of the values? Scanner in = new Scanner (System.in); int max = 0; while (in.hasNextInt()) { int value = in.nextInt(); if (value > max) { max = value; } }

-4 -2 -10 -7

What values does counter variable i take on when this loop executes? for (int i = 20; i >= 2; i = i - 6) { System.out.print(i + ","); }

20, 14, 8, 2, -4

Assume the following variable has been declared and given a value as shown: Random rand = new Random(); int number = rand.nextInt (27) * 2 + 3; What are the smallest and largest values number may be assigned?

3, 55

Assume the following variable has been declared and given a value as shown: Random rand = new Random(); double number = rand.nextDouble () * 2 + 3; What are the smallest and largest values number may be assigned?

3.0, 5.0

Which of the following statements is correct about a sentinel?

A sentinel is a value that indicates the end of an input sequence.

Suppose you must design a program to calculate the roll-out (number of inches travelled in one revolution of the pedals of a bicycle based on its gear combinations). The user will provide the gear sizes, which must be converted into roll-out for all different gear combinations. How can the flow of user interaction for this problem be designed?

A storyboard can be used.

Which statement about storyboards is true?

A storyboard can help prevent potential user confusion early in the design process.

When will the loop in the following code snippet stop? Scanner in = new Scanner(System.in); double sum = 0; int count = 0; System.out.print("Enter values: "); do { double value = in.nextDouble(); sum = sum + value; count++; System.out.print("Enter values, Q to quit: "); } while (in.hasNextDouble() && count < 100); I. when the user enters an integer II. when the user enters an alphabetic character III. after the user enters 100 numbers

II or III

Which of the following should be used when you need to ask a user to enter one data item and repeat the prompt if the data is invalid? I. the for loop II. the while loop III. the do loop

III only

Which of the loop(s) test the condition after the loop body executes? I. the for loop II. the while loop III. the do loo

III only

Which of the statements about hand-tracing is true?

Hand-tracing can be done with pseudocode.

Which of the following loop(s) could possibly not enter the loop body at all? I. the for loop II. the while loop III. the do loop

I and II only

Which loop does not check a condition at the beginning of the loop? I. the do loop II. the while loop III. the for loop

I only

Which of the following activities can be simulated using a computer? I. waiting time in a line at a restaurant II. tossing a coin III. shuffling cards for a card game

I, II, and III

Which of the following statements expresses why the following code is considered bad form? for (rate = 5; years-- > 0; System.out.println(balance)) . . . I. unrelated expressions in loop header II. doesn't match expected for loop idiom III. loop iteration is not clear

I, II, and III

What does the following code do? int sum = 0; final double count = 1000; Random generator = new Random(); for (int i = 1; i <= count; i++) { sum = sum + generator.nextInt(101); } System.out.println(sum / count);

It calculates the average of 1000 random numbers between 0 and 100.

Which of the following statements is true about the variable sum in the code snippet below? int i = 0; while (i != 11) { System.out.print(" " + i); int sum = i; i++; sum++; }

It disappears after the loop is done executing.

What does the following code snippet display? char ch1 = '\u0000'; char ch2 = '\uffff'; for (int i = 0; i < 1000; i++) { if (i % 50 == 0) { System.out.println(); } System.out.print((char)(ch1 + Math.random() * (ch2 - ch1 + 1))); }

It displays random Unicode characters.

Is the code snippet written below legal? (lines are numbered for reference) 1) String s = "1234"; 2) for (int i = 0; i <= 5; i++) 3) { 4) System.out.print(s.substring(i, i + 1)); 5) }

No; for i = 4, s.substring(i, i + 1) will result in an StringIndexOutOfBounds error.

Which of the following is correct for simulating the toss of a pair of coins to get 0 (head) or 1 (tail) with different probabilities? (Assume Random generator = new Random();.)

System.out.println(generator.nextInt(2)+ " " + generator.nextInt(2));

What will be the final output of the following code snippet when a user enters input values in the order 10, 20, 30, 40, 50, and -1? public static void main(String[] args) { double sum = 0; int count = 0; double salary = 0; double average = 0; Scanner reader = new Scanner(System.in); System.out.println("Enter salaries (-1 to stop): "); while (salary != -1) { salary = reader.nextInt(); if (salary != -1) { sum = sum + salary; count++; } } if (count > 0) { average = sum / count; System.out.println("The Average Salary: " + average); } else { System.out.println("No data!"); } return 0; }

The Average Salary: 30.0

What will be the result of running the following code fragment? int year = 0; double rate = 5; double principal = 10000; double interest = 0; while (year < 10) { interest = (principal * year * rate) / 100; System.out.println("Interest " + interest); }

The code fragment will continue to display the calculated interest forever because the loop will never end.

The code snippet below checks whether a given number is a prime number. What will be the result of executing it? public static void main(String[] args) { int j = 2; int result = 0; int number = 0; Scanner reader = new Scanner(System.in); System.out.println("Please enter a number: "); number = reader.nextInt(); while (j <= number / 2) (number % j == 0) { result = 1; } j++; } if (result == 1) { System.out.println("Number: " + number + " is Not Prime."); } else { System.out.println("Number: " + number + " is Prime. "); } }

The code snippet will display the desired result.

Which statement is correct about the execution of the loop in the following code fragment? double num; int incr = 0; Scanner reader = new Scanner(System.in); do { incr = incr + 1; System.out.println("Please enter a number (0 when done): "); num = reader.nextDouble(); } while (num != 0); System.out.println("" + incr);

The loop will execute at least once even if the user has entered the sentinel value.

Which statement about this code snippet is accurate? int years = 50; double balance = 10000; double targetBalance = 20000; double rate = 3; for (int i = 1; i <= years; i++) { if (balance >= targetBalance) { i = years + 1; } else { double interest = balance * rate / 100; balance = balance + interest; } }

The loop will run at most 50 times, but may stop earlier when balance exceeds or equals targetBalance.

What will be the output of the following code snippet? int i; int j; for (i = 0; i <7; i++) { for (j = 7; j > i; j--) { System.out.print("*"); } System.out.println(""); }

The output will be a right triangle with six rows and seven columns of asterisks. The number of columns decrements by one on completion of one iteration of the inner loop.

When hand-tracing a portion of code, which statement about Boolean conditions is true?

They are crucial to evaluate since they determine if-statement conditions and looping control.

What is the best strategy for avoiding off-by-one errors?

Think through a couple of test cases and use the results to come up with a rationale for decisions.

Which statement about using a debugger is correct?

When the program terminates, the debugger stops as well.

s the following code snippet legal? boolean b = false; do { System.out.println("Do you think in Java?"); } while (b != b);

Yes, it is legal and prints "Do you think in Java?" once.

Suppose that a program asks a user to enter multiple integers, either positive or negative, to do some calculation. The data entry will stop when the user enters a certain value to indicate the end of the data. What value should the program use as the sentinel?

an alphabetic character

What will be the range of the What is the name of the special program that lets you find bugs in your code by following its execution? Random generator = new Random(); int r1 = generator.nextInt(50) + 1;;

between 1 and 50

Given the following code snippet, what should we change to have 26 alphabet characters in the string str? String str = ""; for (char c = 'A'; c < 'Z'; c++) { str = str + c; }

c <= 'Z'

What is the name of the special program that lets you find bugs in your code by following its execution?

debugger

Which statement, inserted at the indicated blank line, will correctly terminate this loop when the end of input is reached (detected when the user enters the letter Q)? ArrayList<Double> data = new ArrayList<Double>(); boolean done = false; while (!done) { String input = in.next(); if (input.equalsIgnoreCase("Q")) { __________ } else { double x = Double.parseDouble(input); data.add(x); } }

done = true;

What is the data type of the number generated by the Random.nextDouble() method?

double

Consider the following loop: int n = 1; double x = 0; double s; do { s = 1.0 / (n * n); x = x + s; n++; } while (s > 0.01); System.out.println(x); Which loop below is an equivalent loop?

double x = 0; double s = 1; for (int k = 1; s > 0.01; k++) { s = 1.0 / (k * k); x = x + s; } System.out.println(x);

What is the purpose of the following loop? int upperCaseLetters = 0; int position; String str = "abcdEfghI"; boolean found = false; for (position = 0; position < str.length() && !found; position++) { char ch = str.charAt(position); if (Character.isUpperCase(ch)) { found = true; } }

finds the position of the first uppercase character in a string, starting from the left

In the __________ loop header, you can include multiple update expressions, separated by commas, but it is not recommended.

for

Assuming the variable n is an integer that stores a positive value, which of the following is a loop with a bound that could be problematic?

for (i = 1; i != n; i++)

Which of the following for loops is illegal?

for (int i = 0) { }

What for loop can be used in the indicated area so the code will print: **** *** ** * for (int val = 0; val < 4; val ++) { // Put for loop here { System.out.print("*"); } System.out.println(); }

for (int num = 0; num < 4 - val; num++)

Which of the following loops for will print the odd numbers between 0 and 20?

for (int num = 1; num < 20; num+= 2) { System.out.print(num + " "); }

Suppose that the chance to hit the jackpot in a lottery is one in one million. Which of the expressions simulates that random number? (Assume Random generator = new Random();.)

generator.nextDouble() * 1000000

The for loop header can contain multiple variables of the same type and multiple update expressions, separated by commas: for (int i = 0; j = 3; i <= 5; i++, j--) Which loop below correctly implements the same loop using a single counter in the loop control?

int j = 3; for (int i = 0; i <= 5; i++) { . . . j--; }

Which of the following is the correct code snippet for throwing a pair of dice to get a sum of the numbers on two dice between 2 and 12 with different probabilities? (Assume Random generator = new Random();)

int sum = generator.nextInt(6) + generator.nextInt(6) + 2

Which of the following code snippets will generate a random number between 0 (inclusive) and 79 (inclusive)? (Assume Random generator = new Random();.)

int val = generator.nextInt(80);

The process of hand-tracing code is valuable because

it gives valuable insight that you do not get by running the code.

When designing storyboards, it is a good idea to use different colors to

make it easy to distinguish between user input and program output.

The "divide-and-conquer" strategy for using a debugger helps to

pinpoint the location of an error in the code.

Assume the following variable has been declared and given a value as shown: Random rand = new Random(); Which of the following will generate a random integer in the range - 20 to 20, inclusive, where each value has an equal chance of being generated?

rand.nextInt(41) - 20

The command line interface of your operating system provides a way to link a file to the input of a program. What is this process called?

redirection

Which error type does the "off-by-one" error belong to?

run-time error

What debugger command allows you to make the program execution stop at a specific line of code?

set breakpoint

Which of the following conditions can be added to the code below so it will loop until the value of sum is greater than 100? Scanner in = new Scanner (System.in); int sum = 0; do { sum += in.nextInt(); } while (/* put condition here */);

sum <= 100

What does the following loop compute? Scanner in = new Scanner(System.in); int sum = 0; int count = 0; while (in.hasNextInt()) { int value = in.nextInt(); if (value > 0) { sum += value; count++; } } double result = (sum * 1.0)/count;

the average of all the positive integers in the input

Storyboards are a helpful part of the design process because the storyboard develops

the information needed to solve the problem, and how to present that information.

Which for loop prints data across each row in the following code snippet? int i; int j; for (i = 1; i <= 3; i++) { for (j = 1; j <= 3; j++) { System.out.print("X"); } System.out.println(""); }

the inner for loop

What does the method below return? public static int findSomething(String str) { int position = 0; while (position < str.length() && (str.charAt(position) != 'e')) { position++; } return position; }

the position of the first 'e' in the string or the length of the string if there is no 'e'

When hand tracing, drawing a line through the value stored in a variable means that the

value stored there has changed to something new.

In the following code snippet, when does the execution of the program switch from the inner loop to the outer loop? int i; int j; for (i = 0; i <= 9; i++) { for (j = 1; j < 5; j++) { System.out.println("Hello"); } }

when the value of j becomes 5

In the following code snippet, when does the execution of the program switch from the inner loop to the outer loop? int i; int j; for (i = 0; i <= 9; i++) { for (j = 1; j < 5; j++) { System.out.println("Hello"); if (j == 2) { j = 6; } } }

when the value of j becomes 6

How do you fix this code snippet to make it print out the sum when the user enters a letter rather than a double? The user must enter at least one double when the program begins. System.out.print("Enter a value: "); double sum = 0; Scanner in = new Scanner(System.in); boolean hasData = true; do { double value = in.nextDouble(); sum = sum + value; System.out.print("Enter a value to add, or a letter to quit: "); } while (in.hasNext()); System.out.println("sum " + sum);

while (in.hasNextDouble());

This code snippet is intended to calculate the balance of an account after twenty years of gaining interest. Select the statement that correctly completes the loop. int years = 20; double balance = 10000; while (years > 0) { __________ double interest = balance * rate / 100; balance = balance + interest; }

years--;


Kaugnay na mga set ng pag-aaral

Anxiety and Obsessive-Compulsive Related Disorders

View Set

PrepU Health Assess Ch. 1 Assignment 1

View Set

System Integration and Performance Questions

View Set

Business Education: Content Knowledge (5101)

View Set

Match the Terms in column B with the appropriate description in column A

View Set

Chapter 2: Principles of Physical Fitness

View Set

Lección 14 Lesson Test 2 Study Guide (all corrected)

View Set