Chapter 3.1: Control Structures

Chapter 3.1: Control Structures · Study Questions
Sequential operationsif and else-ifswitchTemperatureLoopsNested loopsbreak and continue
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Sequential Operations

Question 1: A Sequential Swap

We want to swap the values of two variables. What does the program print?

int a = 5, b = 9;
a = b;
b = a;
System.out.println(a + " " + b);

C: Statements run in order: a = b makes a 9 and the value 5 is lost; b = a writes 9 into b again. A swap needs a third variable: int t = a; a = b; b = t;

Multiple Choice · Decision Structures

Question 2: if and else-if Without Braces

Which lines does the program print?

int t = 25;
if (t > 30)
    System.out.println("hot");
    System.out.println("drink water");
if (t > 20) {
    System.out.println("warm");
} else if (t > 10) {
    System.out.println("cool");
}

A: Without braces, only the first statement belongs to the if: "hot" is skipped, and "drink water" is printed whatever the condition. In an else-if chain the block of the first true condition runs and the rest are skipped: 25 > 20 → only "warm".

Multiple Choice · Decision Structures

Question 3: A Range Check

Which condition correctly tests that the variable int score is between 60 and 89 (both inclusive)?

D: Both conditions must hold together: &&. 60 <= score < 90 does not compile: 60 <= score produces a boolean, and a boolean cannot be compared with 90. With || every number satisfies the condition. In the last one, the part inside the parentheses is never true (no number is both below 60 and 90 or above), so its negation is always true.

Multiple Choice · Decision Structures

Question 4: Thresholds in a Rigged Game

The game should print "You win!" with 25% probability, "You lose!" with 35%, and "Try again." with 40%. nextDouble() gives a uniformly distributed number in [0, 1). Which threshold goes in the blank?

Random r = new Random();
double probability = r.nextDouble();
if (probability < 0.25) {
    System.out.println("You win!");
} else if (probability < ____) {
    System.out.println("You lose!");
} else {
    System.out.println("Try again.");
}

C: Only values that fail the first condition (probability ≥ 0.25) reach the else-if condition, so the thresholds are cumulative. The interval [0.25, 0.60) has width 0.35, and the rest, [0.60, 1), has 0.40. With 0.35 the shares would be 25% / 10% / 65%, with 0.40 25% / 15% / 60%, and with 0.75 25% / 50% / 25%.

Spot the Bug · Decision Structures

Question 5: A Wrongly Ordered Chain

The program should print A for 95. What does it print, and why? How do you fix it?

int score = 95;
String letter;
if (score >= 60) letter = "D";
else if (score >= 70) letter = "C";
else if (score >= 90) letter = "A";
else letter = "F";
System.out.println(letter);
Show answer

Output: D. And D for every score of 60 or more.

  • The else-if conditions are tested from top to bottom; the block of the first true condition runs and the rest are never looked at.
  • Since 95 >= 60 is true, the first branch is chosen; the score >= 90 branch can never be reached.
  • The fix: order the conditions from largest to smallest.
if (score >= 90) letter = "A";
else if (score >= 70) letter = "C";
else if (score >= 60) letter = "D";
else letter = "F";

The compiler does not catch this error: it is a logic error.

Multiple Choice · switch

Question 6: Which switch Compiles?

Which of the following fragments compiles?

B: The selector can be a String (Java 7+). A double (also long, float, boolean) cannot be a selector. A case value must be a constant known at compile time; b is a non-final variable. The same value cannot be used in two cases (duplicate case label).

Output Question · switch

Question 7: Seasons and Fall-Through

W is winter, S is spring, M is summer, F is fall. Which months does the loop try, and what does the program print?

String result = "";
for (int month = 1; month <= 12; month += 4) {
    switch (month) {
        case 12: case 1: case 2:
            result += "W"; break;
        case 3: case 4: case 5:
            result += "S";
        case 6: case 7: case 8:
            result += "M"; break;
        default:
            result += "F";
    }
}
System.out.println(result);
Show answer

Output: WSMF

  • month += 4: the loop runs for 1, 5 and 9 (13 <= 12 is false).
  • month = 1: the winter group, break → "W".
  • month = 5: "S" is appended but there is no break; the flow falls through to the summer group and "M" is appended too.
  • month = 9: no case matches → default → "F".

Consecutive labels such as case 3: case 4: case 5: are the form in which fall-through is used on purpose.

Multiple Choice · Temperature

Question 8: Fahrenheit and Integers

For int c = 37;, which expression gives 98 (37 °C ≈ 98.6 °F)?

A: Left to right: 37 · 9 = 333, 333 / 5 = 66 (the fraction is dropped), + 32 = 98. If 9 / 5 is computed first it is 1: 37 + 32 = 69. c / 5 = 7 → 7 · 9 + 32 = 95. The last expression is a wrong formula: 124. For a fractional result, write c * 1.8 + 32.

Multiple Choice · Loops

Question 9: Accumulating a Product

What does the program print?

int number = 5;
int result = 1;
while (number > 0) {
    result *= number;
    number--;
    System.out.print(result + " ");
}

D: The loop runs five times, for number = 5, 4, 3, 2, 1, and prints one value per round. Since the multiplication happens before printing, the first value is 5 (1 is never printed). In the last round 120 · 1 = 120, so 120 appears twice. After the loop, result = 5! = 120 and number = 0.

Multiple Choice · Loops

Question 10: The Digit Count of Zero

The digit-counting loop finds 0 for number = 0. Which change counts 0 as a 1-digit number and still gives the right result for other positive numbers?

int count = 0;
while (number > 0) {
    number = number / 10;
    count++;
}

B: do-while runs the body at least once: 0 → 1 digit, 1234 → 4 digits. number >= 0 is never false (0 / 10 = 0): an infinite loop. Starting the counter at 1 counts one too many for every positive number. The order of the lines does not change the result.

Step-by-Step Trace · Loops

Question 11: Tracing a Reversal

% 10 takes the last digit, / 10 removes it. Trace the variables after each round. What does the program print?

The accumulator for the sum is 0; the reversed number will also be built up from 0.

4071 % 10 = 1. reversed = 0 · 10 + 1 = 1. 4071 / 10 = 407.

digit 7: reversed = 1 · 10 + 7 = 17; sum 8.

digit 0 does not change the sum but adds a place to reversed: 170.

digit 4: reversed = 1704, sum = 12, number is now 0.

0 > 0 is false: the loop ends. digit was declared in the block and no longer exists.

The digits arrive from right to left, so the reversed number is formed. If the original number were needed, it would have to be copied first.

int number = 4071;
int reversed = 0, sum = 0;
while (number > 0) {
    int digit = number % 10;
    reversed = reversed * 10 + digit;
    sum += digit;
    number = number / 10;
}
System.out.println(reversed + " " + sum);

Coding Question · Loops

Question 12: Digital Root

Write, with nested while loops, code that adds up the digits of a number and repeats until the result is a single digit (the digital root). What is the result for 98765 and for 999999999?

Show answer
int number = 98765;
while (number >= 10) {
    int sum = 0;
    while (number > 0) {
        sum += number % 10;
        number = number / 10;
    }
    number = sum;
}
System.out.println(number);
  • The outer loop runs until the number has a single digit. The inner loop computes the sum of the digits. sum must start from 0 again in every outer round.
  • 98765 → 35 → 8. 999999999 → 81 → 9.

Multiple Choice · Loops

Question 13: How Many Rounds of do-while?

What does the program print?

int k = 10, count = 0;
do {
    k -= 4;
    count++;
} while (k > 0);
System.out.println(k + " " + count);

B: k: 10 → 6 → 2 → −2. The condition is tested at the end of each round: 6 > 0 and 2 > 0 are true, −2 > 0 is false. The body runs 3 times and k drops below the limit.

Multiple Choice · Nested Loops

Question 14: Alignment with printf

What does System.out.printf("[%3d][%-3d][%02d]%n", 7, 7, 7); print?

A: %3d right-aligns in a 3-character field, %-3d left-aligns; %02d prints at least 2 digits and pads the missing ones with 0 on the left. When every cell in a table has the same width, the columns line up.

Spot the Bug · Nested Loops

Question 15: A Plus-Minus Pattern

We want a 3-row pattern where every row is +-+-+-+-+-+-+-+-+-+- ("+-" repeated 10 times). Does the code print this pattern? If not, how do you fix it?

int rows = 3;
int length = 21; // characters per row
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < length; j++) {
        if (j % 2 == 0) {
            System.out.print("+");
        } else {
            System.out.print("-");
        }
    }
    System.out.println();
}
Show answer

No. Every row gets +-+-+-+-+-+-+-+-+-+-+: 21 characters, with an extra "+" at the end.

  • The inner loop runs 21 rounds for j = 0 … 20: the even j's (0, 2, …, 20) give 11 "+" and the odd j's give 10 "-".
  • The wanted row has 20 characters: with length = 20, j = 0 … 19, the last j = 19 is odd and the row ends with "-".
  • Another fix: run the inner loop 10 times and print System.out.print("+-"); in each round.

With boundary errors, it helps to check the value of j in the last round and the character printed, one by one.

Output Question · Nested Loops

Question 16: A Number Pyramid

The outer loop prints the rows; the three inner loops print the spaces, the ascending digits and the descending digits, in that order. What is the output? How many characters does row i have?

for (int i = 1; i <= 4; i++) {
    for (int j = 1; j <= 4 - i; j++)
        System.out.print(" ");
    for (int j = 1; j <= i; j++)
        System.out.print(j);
    for (int j = i - 1; j >= 1; j--)
        System.out.print(j);
    System.out.println();
}
Show answer
   1
  121
 12321
1234321
  • In row i, 4 − i spaces are printed, then 1…i, then i − 1…1.
  • The number of digits is i + (i − 1) = 2i − 1; with the spaces, the row length is (4 − i) + (2i − 1) = i + 3.
  • The third loop does not run at all when i = 1: j = 0 >= 1 is false.

Step-by-Step Trace · Nested Loops

Question 17: Tracing a Grid Pattern

The condition is tested for every cell. Which cells get a #? Trace the output step by step.

j=1j=2j=3i=1#i=2i=3

i = 1, j = 1: i == j is true, and || does not look at the right side → "#".

j=1j=2j=3i=1#.i=2i=3

i = 1, j = 2: both conditions are false → ".".

j=1j=2j=3i=1#.#i=2i=3

j == 3 is true → "#". The inner loop is done; println() ends the line.

j=1j=2j=3i=1#.#i=2.i=3

i = 2, j = 1: both conditions are false → ".".

j=1j=2j=3i=1#.#i=2.#i=3

i == j is true → "#".

j=1j=2j=3i=1#.#i=2.##i=3

j == 3 is true → "#". The inner loop is done; println() ends the line.

j=1j=2j=3i=1#.#i=2.##i=3.

i = 3, j = 1: both conditions are false → ".".

j=1j=2j=3i=1#.#i=2.##i=3..

i = 3, j = 2: both conditions are false → ".".

j=1j=2j=3i=1#.#i=2.##i=3..#

The diagonal and the last column meet here: "#". 3 × 3 = 9 cells in all; the outer loop ends.

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (i == j || j == 3)
            System.out.print("#");
        else
            System.out.print(".");
    }
    System.out.println();
}

Multiple Choice · break and continue

Question 18: i After the Loop

What does the program print?

int i = 0;
for (i = 1; i < 6; i++) {
    if (i > 3)
        continue;
}
System.out.println(i);

C: continue does not end the loop; it only skips the rest of that round, and here there is no statement to skip. The loop ends when i < 6 becomes false, that is, when i = 6. Because i was declared before the loop, this final value can be read after it. With break instead of continue, the loop would exit at i = 4 and print 4.

Step-by-Step Trace · break and continue

Question 19: break and continue in Nested Loops

continue is in the inner loop, break in the outer loop. How many lines does the program print? Which loop does each statement affect?

i = 1: 1 == 3 is false, the inner loop starts. j = 1 is not equal to two, so the line is printed.

j = 2: continue skips the rest of this round of the inner loop; j++ runs, and the outer loop is not affected.

j = 3 is printed.

j = 4 is printed. When j = 5, the inner loop ends and the outer loop does i++.

i = 2: the inner loop starts again from j = 1.

j = 2 is skipped again.

j = 3 and j = 4 are printed; the inner loop ends.

i = 3: break leaves the outer loop it sits in; i = 4 is never tried. 6 lines in total.

for (int i = 1; i <= 4; i++) {
    if (i == 3) break;
    for (int j = 1; j <= 4; j++) {
        if (j == 2) continue;
        System.out.println("i: " + i + " j: " + j);
    }
}

Step-by-Step Trace · break and continue

Question 20: Tracing a Primality Test

A divisor is searched for only while i * i <= number; i is declared before the loop. What does the program print?

91 ≥ 2: it is first assumed to be prime (a flag). i will be used after the loop too.

4 <= 91. 91 % 2 = 1: not a divisor.

9 <= 91. 91 % 3 = 1.

i = 4, 5, 6 do not divide either (remainders 3, 1, 1).

49 <= 91. 91 % 7 = 0: a divisor is found, the flag is lowered.

break: the loop is left at once; i++ does not run, so i stays 7.

91 = 7 · 13. Only 6 trials were made; at i = 10 we would have 100 > 91.

int number = 91;
boolean prime = number >= 2;
int i;
for (i = 2; i * i <= number; i++) {
    if (number % i == 0) {
        prime = false;
        break;
    }
}
System.out.println(number + " " + prime + " " + i);

Spot the Bug · break and continue

Question 21: A Loop Stuck on continue

The goal is to print the numbers other than 2 and then say "done". What does the program do? How do you fix it?

int i = 0;
while (i < 5) {
    if (i == 2) {
        continue;
    }
    System.out.print(i + " ");
    i++;
}
System.out.println("done");
Show answer

It prints 0 1 and then loops forever; "done" is never printed.

  • When i = 2, continue skips the rest of the body, including i++. i stays 2 and the condition is always true.
  • In a while loop the update is inside the body, and continue can skip it. In a for loop the update is in the header and also runs after a continue:
for (int i = 0; i < 5; i++) {
    if (i == 2) {
        continue;
    }
    System.out.print(i + " ");
}
System.out.println("done");

The corrected output: 0 1 3 4 done

The End

Chapter 3.1: Control Structures: Study Questions
Lecture slides: Chapter 3.1: Control Structures · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.