Chapter: Chapter 6: Iteration

Study Guide

Multiple Choice

1. What output does this while loop generate?

j = 1;

while (j > 0)

{

System.out.print(j + ", ");

j++;

}

A) No output is generated.

B) 1, 2, 3, 4, 5, 6,

C) 1, 2, 3, 4, 5,

D) The output is infinite.

2. What output does this while loop generate?

j = 6;

while (j > 0)

{

System.out.print(j + ", ");

j--;

}

A) No output is generated.

B) 6, 5, 4, 3, 2, 1

C) 6, 5, 4, 3, 2, 1,

D) The output is infinite.

3. What output does this while loop generate?

j = 1;

while (j > 1)

{

System.out.print(j + ", ");

j++;

}

A) 1, 2, 3, 4, 5, 6,

B) 1, 2, 3, 4, 5,

C) The output is infinite.

D) No output is generated.

4. What output does this while loop generate?

j = 6;

while (j > 0);

{

System.out.print(j + ", ");

j--;

}

A) 6, 5, 4, 3, 2, 1

B) The output is infinite.

C) No output is generated.

D) 6, 5, 4, 3, 2, 1,

5. What output does this while loop generate?

j = 6;

while (j > 0)

{

System.out.print(j + ", ");

}

A) 6, 5, 4, 3, 2, 1

B) The output is infinite.

C) 6, 5, 4, 3, 2, 1,

D) No output is generated.

6. Insert the missing statement in the following code fragment. The loop is intended to keep prompting until the user enters a positive number.

boolean done = false;

while (______)

{

System.out.print("Please enter a positive number: ");

value = in.nextDouble();

if (value > 0) done = true;

}

A) value <= 0

B) done

C) value > 0

D) !done

7. Insert the missing statement in the following investment loop code fragment.

int years = 20;

while (years > 0)

{

______

double interest = balance * rate / 100;

balance = balance + interest;

}

A) years--;

B) years == years - 1;

C) years == years + 1;

D) years++;

8. What type of error occurs when a loop runs forever and can be stopped only by killing the program or restarting the computer?

A) fence post

B) infinite loop

C) off-by-one

D) loop and a half

9. What error does this while loop illustrate?

j = 6;

while (j > 0)

{

System.out.print(j + ", ");

j++;

}

A) fence post

B) off-by-one

C) infinite loop

D) There is no error in the code.

10. What type of loop is executed at least once?

A) while

B) do

C) off-by-one

D) for

11. Insert the missing statement in the following code fragment so that it correctly prompts the user to enter a positive number.

double value;

do

{

System.out.print("Please enter a positive number: ");

value = in.nextDouble();

}

______

A) while (value <0);

B) while (value >= 0);

C) while (value <= 0);

D) while (value > 0);

12. Consider the following code fragment:

do

input = JOptionPane.showInputDialog("Do you want to continue (Y or N): ");

while (input != null & !input.equals("Y") & !input.equals("N"));

What should the while condition be when the do loop is changed to a while loop, assuming input is initially an empty string?

A) (input != null || !input.equals("Y") & !input.equals("N"))

B) (input == null || input.equals("Y") || input.equals("N"))

C) (input != null & !input.equals("Y") || !input.equals("N"))

D) (input != null & !input.equals("Y") & !input.equals("N"))

13. Which for loop is equivalent to the given while loop?

i = 1;

while (i <= 5)

{

. . .

i++;

}

A) for (i = 1; i < 5; i++) { ... }

B) for (i = 1; i >= 5; i++) { ... }

C) for (i = 1; i <= 5; i++) { ... }

D) for (i = 1; i != 5; i++) { ... }

14. A(n) ___ loop is appropriate for a definite number of iterations.

A) while

B) for

C) infinite

D) nested

15. Which loop is preferred when a variable runs from a starting to an ending value with a constant increment or decrement?

A) infinite

B) for

C) nested

D) while

16. Which statement completes this investment loop?

for (years = 1;

(balance = balance + balance * rate / 100) < targetBalance;

years++)

______

A) :

B) ;

C) balance++;

D) years--;

17. The following loop alters the control variable i. Which values does i assume?

for (int i = 20; i >= 2; i = i - 6) . . .

A) 14, 8, 2

B) 20, 14, 8, 2

C) 20, 14, 8

D) 20, 14, 8, 2, -4

18. Fill in the blank to complete this common use of the for loop.

for (int ______; i < str.length(); i++)

{

char ch = str.charAt(i);

// Process ch

}

A) i = 0

B) i = 1;

C) i = 0;

D) i = 1

19. What output is generated by this for loop?

String str = "";

for (int i = 0; i <= str.length() - 1; i++)

{

System.out.println(str.charAt(i) + "-");

}

A) ---

B) No output is generated.

C) --

D) –

20. What output is generated by this for loop?

for (int i = 1; i <= 50; i = i * 2)

System.out.println(i);

A) No output is generated.

B) 1, 2, 4, 8, 16

C) 2, 4, 8, 16, 32

D) 1, 2, 4, 8, 16, 32

21. What output is generated by this code fragment involving a for loop?

int i = 0;

int sum = 0;

for (i = 1; i <= 6; i++);

sum = sum + i;

System.out.println(sum);

A) The output is infinite.

B) 21

C) None because the code does not compile.

D) 7

22. Which for loop header has a hidden danger?

A) for (years = n; years > 0; years--)

B) for (i = 1; i <= n; i++)

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

D) for (int i = 20; i >= 2; i = i - 6)

23. What output does this for loop generate?

for (int i = 1; i <= 5; i++)

{

System.out.print(i + " ");

}

System.out.println(i + 1);

A) 1 2 3 4 5

B) The output is infinite.

C) None because the code does not compile.

D) 1 2 3 4 5 6

24. Which for loop header has symmetric bounds?

A) for (i = 1; i <= n; i++)

B) for (i = 10; i < 40; i += 5)

C) for (i = a; i < b; i++)

D) for (i = 0; i < str.length(); i++)

25. Which for loop header has asymmetric bounds?

A) for (i = 1; i <= n; i++)

B) for (i = a; i <= b; i++)

C) for (i = 10; i <= 40; i += 5)

D) for (i = 0; i < str.length(); i++)

26. Forgetting to count the last iteration of a for loop involving <= is often called a _____.

A) bad programming style

B) infinite loop

C) syntax error

D) fence-post error

27. How many iterations does the following for loop execute?

for(x = 0; x <= 10; x++) . . .

A) 10

B) 12

C) 11

D) 9

28. How many iterations does the following for loop execute?

for (i = 1; i <= 25; i++)

System.out.println( i * i);

A) 26

B) 25

C) 24

D) 6

29. How many iterations does the following for loop execute?

for (x = 1; x <= 50; x = x * 2) . . .

A) 4

B) 7

C) 6

D) 5

30. How many iterations does the following for loop execute?

for(x = 0; x < 100; x += 5) ...

A) 21

B) 19

C) 20

D) 0

31. Fill in the missing for loop header to compute pow(a, n).

int power = 1;

for ______

power = power * a;

A) (int f = 1; f < n; f++)

B) (int p = 1; p < n; p++)

C) (int f = n; f > 0; f--)

D) (int p = 1; p <= n; p++)

32. Fill in the missing for loop header to compute n! (n factorial). The factorial of a number n is the product n * (n – 1) * ... * 2 * 1.

int factorial = 1;

for ______

factorial = factorial * f;

A) (int f = 1; f < n; f++)

B) (int i = 1; i <= n; i++)

C) (int i = n; i > 0; i--)

D) (int f = n; f > 0; f--)

33. Consider the following pseudocode for constructing the reverse of an input string:

For each position of the string starting at the end working backwards

Append the character at that position to the reverse of the string.

Which is the correct for loop header for this pseudocode?

A) for (int i = input.length() - 1; i >= 0; i--)

B) for (int i = 0; i <= input.length() - 1; i++)

C) for (int i = input.length(); i > 0; i--)

D) for (int i = input.length() - 1; i > 0; i--)

34. Consider the following pseudocode for constructing the reverse of an input string:

For each position of the string starting at the end working backwards

Append the character at that position to the reverse of the string.

Which is the correct loop body for this pseudocode, assuming that reverse has been declared and initialized to the empty string?

A) reverse = reverse + input.stringAt(i);

B) reverse = input.charAt(i) + reverse;

C) reverse = reverse + input.charAt(i);

D) reverse = input.charAt(i);

35. Consider the following pseudocode for removing dashes from a phone number:

For each position of the phone number starting at the beginning

If the character is not a dash

Append the character at that position to the phone number without dashes.

Which is the correct for loop header for this pseudocode?

A) for (int i = 0; i < phoneNumber.length(); i++)

B) for (int i = phoneNumber.length() - 1; i > 0; i--)

C) for (int i = 0; i <= phoneNumberNoDashes.length() - 1; i++)

D) for (int i = phoneNumber.length(); i > 0; i--)

36. Consider the following pseudocode for removing dashes from a phoneNumber:

For each position of the phone number starting at the beginning

If the character is not a dash

Append the character at that position to the phone number without dashes.

Which is the correct if condition for the pseudocode?

A) if (phoneNumber.charAt(i) == '-')

B) if (phoneNumber.charAt(i).equals('-'))

C) if (!phoneNumber.charAt(i).equals('-'))

D) if (phoneNumber.charAt(i) != '-')

37. Consider the following pseudocode for removing dashes from a phoneNumber:

For each position of the phone number starting at the beginning

If the character is not a dash

Append the character at that position to the phone number without dashes.

Which is the correct loop body for the pseudocode, assuming that numberNoDashes has been declared and initialized to the empty string?

A) numberNoDashes = numberNoDashes + phoneNumber.charAt(i);

B) numberNoDashes = phoneNumber.charAt(i);

C) numberNoDashes = phoneNumber.charAt(i) + numberNoDashes;

D) numberNoDashes = numberNoDashes + phoneNumber.stringAt(i);

38. What is the purpose of the following algorithm?

double j = 0;

while (in.hasNextDouble())

{

double input = in.nextDouble();

j = j + input;

}

A) counting matches

B) prompting until a match is found

C) comparing adjacent values

D) computing a total

39. What is the purpose of the following algorithm?

int digits = 0;

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

{

char ch = str.charAt(i);

if (Character.isDigit(ch))

{

digits++;

}

}

A) prompting until a match is found

B) counting matches

C) computing a total

D) comparing adjacent values

40. Complete the for loop header for this algorithm that counts the number of digits in a string.

int digits = 0;

for (______)

{

char ch = str.charAt(i);

if (Character.isDigit(ch))

{

digits++;

}

}

A) int i = 1; i <= str.length(); i++

B) int i = 0; i < str.length(); i++

C) int i = 0; i < str.size(); i++

D) int i = 1; i <= str.size(); i++

41. What is the purpose of the following algorithm?

boolean found = false;

int i = 0;

while (!found & i < str.length())

{

ch = str.charAt(i);

if (ch == '-') { found = true; }

else { i++; }

}

A) finding the first match

B) prompting until a match is found

C) counting matches

D) comparing adjacent values

42. Insert a while condition for this algorithm that finds the first occurrence of a dash in the string.

boolean found = false;

int i = 0;

while (______)

{

ch = str.charAt(i);

if (ch == '-') { found = true; }

else { i++; }

}

A) !found & i < str.length()

B) found & i < str.length()

C) found & i <= str.length()

D) !found & i <= str.length()

43. What is the purpose of the following algorithm?

boolean found = false;

int i = str.length() - 1;

while (!found & i > 0)

{

ch = str.charAt(i);

if (ch == '-') { found = true; }

else { i--; }

}

A) counting matches

B) comparing adjacent values

C) finding the last match

D) prompting until a match is found

44. What is the purpose of the following algorithm?

boolean valid = false;

int input;

while (!valid)

{

System.out.print("Please enter a number between 1 and 10: ");

input = in.nextInt();

if (0 < input & input <= 10) { valid = true; }

else { System.out.println("Invalid input."); }

}

A) comparing adjacent values

B) finding the first match

C) counting matches

D) prompting until a match is found

45. Insert a while condition for this algorithm that prompts until a valid value is entered.

boolean valid = false;

int input;

while (______)

{

System.out.print("Please enter a number between 1 and 10: ");

input = in.nextInt();

if (0 < input & input <= 10) { valid = true; }

else { System.out.println("Invalid input."); }

}

A) invalid

B) input > 10

C) valid

D) !valid

46. What is the purpose of the following algorithm?

int input = in.nextInt();

while (in.hasNextInt())

{

int p = input;

input = nextInt();

if (input == p) { System.out.println("Duplicate input"); }

}

A) finding the first match

B) prompting until a match is found

C) comparing adjacent values

D) counting matches

47. Insert a while condition for this algorithm that compares adjacent values.

int input = in.nextInt();

while (______)

{

int p = input;

input = nextInt();

if (input == p) { System.out.println("Duplicate input"); }

}

A) in.nextInt()

B) !in.hasNextInt()

C) !in.nextInt()

D) in.hasNextInt()

48. What term is used to represent a value that indicates the end of a data set?

A) finite

B) sentinel

C) end

D) fence

49. Insert a statement to terminate this loop when the end of input is reached.

boolean done = false;

while (!done)

{

String input = in.next();

if (input.equalsIgnoreCase("Q"))

______

else

{

double x = Double.parseDouble(input);

data.add(x);

}

}

A) done = true;

B) done = "Yes";

C) done = "Q";

D) done == true;

50. What is the purpose of the following algorithm?

int input = in.nextInt();

int m = input;

while (in.hasNextInt())

{

input = nextInt();

if (input > m) { m = input; }

}

A) prompting until a match is found

B) finding the minimum value

C) finding the first match

D) finding the maximum value

51. Which statement completes this algorithm for finding the minimum value?

int input = in.nextInt();

int m = input;

while (in.hasNextInt())

{

input = nextInt();

______;

}

A) if (input < m) { input = m; }

B) if (input < m) { m = input; }

C) if (input < m) { m == input; }

D) if (input > m) { m = input; }

52. What is the purpose of the following algorithm, assuming s references a String?

boolean valid = (s != null);

int i = 0;

char ch;

while (valid & i < s.length())

{

ch = s.charAt(i);

valid = Character.isDigit(ch);

i++;

}

A) verifies that the string contains all digits

B) finds the first digit in the string

C) counts the number of digits in the string

D) finds the last digit in the string

53. A loop that requires you to go halfway into it before knowing whether or not to terminate is often called a(n) ______.

A) fence post

B) infinite loop

C) off-by-one

D) loop and a half

54. Few programmers use the _____ statement, which jumps to the end of the current iteration of the loop.

A) continue

B) jump

C) label

D) exit

55. When the body of a loop contains another loop, the loops are ______.

A) nested

B) asymmetric

C) spaghetti code

D) symmetric

56. Consider the following pseudocode for dealing cards to players in a card game:

For the required number of cards

For the required number of players

Deal a card.

Which statement corresponds to the outer loop of the pseudocode?

A) for (int players=1; players < NUMBER_OF_PLAYERS; players++)

B) for (int cards=1; cards <= NUMBER_OF_CARDS; cards++)

C) for (int cards=1; cards < NUMBER_OF_CARDS; cards++)

D) for (int players=1; players <= NUMBER_OF_PLAYERS; players++)

57. Consider the following pseudocode for dealing cards to players in a card game:

For the required number of cards

For the required number of players

Deal a card.

Which statement corresponds to the inner loop of the pseudocode?

A) for (int cards=1; cards < NUMBER_OF_CARDS; cards++)

B) for (int players=1; players < NUMBER_OF_PLAYERS; players++)

C) for (int cards=1; cards <= NUMBER_OF_CARDS; cards++)

D) for (int players=1; players <= NUMBER_OF_PLAYERS; players++)

58. Consider the following pseudocode for rolling dice in a game:

For the required number of players

For the required number of dice

Roll the die.

Which statement corresponds to the inner loop of the pseudocode?

A) for (int players=1; players <= NUMBER_OF_PLAYERS; players++)

B) for (int d=1; d <= NUMBER_OF_DICE; d++)

C) for (int d=1; d < NUMBER_OF_DICE; d++)

D) for (int players=1; players < NUMBER_OF_PLAYERS; players++)

59. A ____ program uses the computer to imitate an activity in the real world.

A) debugging

B) interactive

C) simulation

D) imitation

60. In the following code segment, the value d is set to a random integer between ____.

Random generator = new Random();

int d = generator.nextInt(100);

A) 0 and 99

B) 1 and 100

C) 1 and 99

D) 0 and 100

61. Assume that generator has been initialized to an instance of class Random. Which of the following calls returns a random integer between 0 and n inclusive?

A) generator.nextInt(n + 1)

B) generator.nextInt(n + 1) - 1

C) generator.nextInt(n)

D) generator.nextInt(n) + 1

62. Consider the following pseudocode that simulates guessing a number between 1 and 10 inclusive:

Make a guess between 1 and 10 inclusive

until the guess matches the number

What type of loop is recommended?

A) for

B) Iteration is not recommended.

C) until

D) do

63. Consider the following pseudocode that simulates guessing a number between 1 and 10 inclusive:

Make a guess between 1 and 10 inclusive

until the guess matches the number

Which statement simulates guessing a number between 1 and 10?

A) guess = generator.nextInt(10) + 1;

B) guess = generator.nextInt(11);

C) guess = generator.nextInt(10);

D) guess = generator.nextInt(10 + 1);

64. Consider the following pseudocode that simulates guessing a number between 1 and10 inclusive:

do

make a guess between 1 and 10 inclusive

until the guess matches the number

Which statement correctly terminates the loop?

A) until (guess == number);

B) while (guess == number)

C) until guess = number;

D) while (guess != number);

65. Consider the following pseudocode for simulating the roll of a die a fixed number of times:

Do the following 5 times:

Roll the die.

Add value to total.

What type of loop is recommended?

A) while

B) Iteration is not recommended.

C) for

D) do

66. Consider the following pseudocode that simulates rolling a die 5 times:

Do the following 5 times:

Roll the die.

Add value to total.

Which statement corresponds to rolling the die?

A) die = generator.nextInt(7) - 1;

B) die = generator.nextInt(6) + 1;

C) die = generator.nextInt(5) + 1;

D) die = generator.nextInt(7);

67. Consider the following pseudocode that simulates rolling a die 5 times:

Do the following 5 times:

Roll the die.

Add value to total.

Which statement correctly constructs the loop?

A) for (int i = 1; i = 5; i++)

B) while (int i = 1; i <= 5; i++)

C) for (int i = 1; i <= 5; i++)

D) do (int i = 1; i <= 5; i++)

68. Consider the following pseudocode for simulating counting players onto teams numbered 1 to 4:

For each player:

Count off which team.

Which statement correctly constructs the loop for each player?

A) for (int p = 1; p < NUMBER_OF_PLAYERS; p++)

B) for (int p = 0; p < NUMBER_OF_PLAYERS; p++)

C) for (int p = 0; p <= NUMBER_OF_PLAYERS; p++)

D) for (int p = 1; p <= NUMBER_OF_PLAYERS; p++)

69. Consider the following pseudocode for simulating counting players onto teams numbered 1 to 4:

For each player:

Count off which team.

Which statement correctly simulates counting the player onto a team, assuming p is the number of the player?

A) team = (p % 4) != 0 ? (p % 4) : 4;

B) team = (p mod 4) != 0 ? (p mod 4) : 4;

C) team = (p % 4);

D) team = (p mod 4);

70. When a debugger executes a program, the execution is suspended whenever a ______is reached.

A) break

B) breakpoint

C) continue

D) single-step

71.The _____ command executes programs one line at a time.

A) inspect

B) single-step

C) breakpoint

D) debug

72. Which single-step command steps inside method calls?

A) continue

B) step into

C) breakpoint

D) step over

73. Which single-step command skips over method calls?

A) step over

B) step into

C) continue

D) breakpoint

74. Which of the following is used as a strategy to locate the point of failure of a program?

A) divide and conquer

B) iteration

C) enumeration

D) simulation

75. Which of the following statements about debugging is correct?

A) The larger your programs get, the easier it is to debug them.

B) You can make effective use of a debugger by mastering just three concepts: breakpoints, single-stepping, and inspecting variables.

C) During debugging, you don't need to compare the actual contents of variables against the values you know they should have.

D) A debugger can be used to show that a program is bug-free.