Chapter 3.1: Control Structures

Object Oriented Programming with Java
Sequential executionif-elseelse-if chainsNested decisions switch-caseThe for loopwhile and do-while Nested loopsbreak and continue
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Flow of control

Explain how sequence, selection and loops direct the flow of a program.

Decisions

Write conditional code with if, if-else, else if chains, nested decisions and &&/|| conditions.

switch-case

Compare a value against constants; explain what break does and how “fall-through” works.

Loops

Use for, while and do-while where each fits; avoid infinite loops and off-by-one errors.

Nested loops

Count how many times nested loops run in patterns, tables and digit examples.

Tracing

Predict variable values and output by tracing a program step by step; show the effect of break and continue.

Introduction

Control Structures

  • Control structures direct a program's flow: which statements run, in what order, how often.
  • Java has three basic control structures; any program can be built from them:
SequenceStep 1Step 2Step 3

Statements run top to bottom, once each.

Decisionscondition?PQYN

A condition picks one of two (or more) paths: if-else, switch.

Loopscondition?bodyYN

Work repeats while a condition holds: for, while, do-while.

Why it matters: decisions let a program react to different situations and user input; loops automate repetitive work.

Introduction · Step-by-step code trace

Sequential Execution

Code runs top to bottom, line by line; one operation finishes before the next starts. A program with no control structures is sequential.

x5y?result?

The first line runs: x gets 5. The next line does not start until this one finishes.

x5y10result?

Second line: y gets 10.

x5y10result15

The third line uses the results of the first two: 5 + 10 = 15.

x5y10result15

The last line prints the result. If the lines were reordered (e.g. line 3 first), the program would not compile.

int x = 5;
int y = 10;
int result = x + y;
System.out.println(result);

Decisions: if

Making Decisions

  • Decision making means the program chooses which path to follow at run time.
  • It lets the program carry out different actions depending on conditions.
  • In Java this is done with if-else and switch-case.
  • A condition is a true- or false-valued boolean expression.
  • Analogy: a sign at a fork in the road. “If it's raining, take an umbrella; otherwise don't.”
  • Why it matters: the program responds to different situations and user input, the flow is steered, and flexibility increases.
OperatorMeaningExample (x = 7)
==equalx == 7 → true
!=not equalx != 7 → false
< >less / greaterx < 10 → true
<= >=less-or-equal / greater-or-equalx >= 8 → false
= is assignment, == is comparison. if (x = 7) does not compile: the condition must be a boolean.

Decisions: if

The if-else Statement

if (condition) {
    // runs if the condition is true
} else {
    // runs if the condition is false
}
  • First the condition is evaluated.
  • If the condition is true (true), the if block runs and the else block is skipped.
  • If the condition is false (false), the if block is skipped and the else block runs.
  • The else is optional. Of the two blocks, at most one runs.
  • The condition always goes in parentheses: if (condition).
previous statementcondition?if blockelse blocknext statementYN

Decisions: if

if Alone, and Braces

else-less if

int temp = 35;
if (temp > 30) {
    System.out.println("It's hot!");
}
System.out.println("The program continues.");
It's hot!
The program continues.

If the condition were false (e.g. temp = 20), only “The program continues.” would print. After if, the next line always runs.

Pitfall: no braces

int temp = 35;
if (temp > 40)
    System.out.println("Very hot!");
    System.out.println("Drink water.");
Drink water.

Without braces, if owns only the first statement. Indentation means nothing to Java: “Drink water.” runs regardless of the condition. That's why braces { } are used even for one-line blocks.

Decisions: if · Step-by-step code trace

Example: Age Check

age = 18age ≥ 18 ?Print allowedPrint deniedEndYN

age is assigned 18.

age = 18age ≥ 18 ?Print allowedPrint deniedEndYN

The condition is evaluated: 18 >= 18 → true. Flow takes the “Y” (yes) branch.

age = 18age ≥ 18 ?Print allowedPrint deniedEndYN

The if block runs and prints the message.

age = 18age ≥ 18 ?Print allowedPrint deniedEndYN

The else block (line 5) is skipped. age = 16 would make it false, and only “You cannot get a license.” would be printed.

int age = 18;
if (age >= 18) {
    System.out.println("You can get a license.");
} else {
    System.out.println("You cannot get a license.");
}

Decisions: if · Step-by-step code trace

Example: Absolute Value

Read numnum < 0 ?abs = −numabs = numPrint absYN

To read from the keyboard, create a Scanner object (this needs import java.util.Scanner; at the top of the file).

Read numnum < 0 ?abs = −numabs = numPrint absYN

The user is told what to enter. print does not move to a new line; the cursor waits on the same line.

Read numnum < 0 ?abs = −numabs = numPrint absYN

The user types -7,5. On a computer with a Turkish locale the decimal separator is a comma, so -7.5 throws InputMismatchException.

Read numnum < 0 ?abs = −numabs = numPrint absYN

absValue is declared but has no value yet.

Read numnum < 0 ?abs = −numabs = numPrint absYN

Condition: -7.5 < 0 → true.

Read numnum < 0 ?abs = −numabs = numPrint absYN

-num = −(−7.5) = 7.5 is assigned. The else block is skipped.

Read numnum < 0 ?abs = −numabs = numPrint absYN

The result is printed. println, however, always prints a double value with a dot: 7.5.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double num = scanner.nextDouble();
double absValue;
if (num < 0) {
    absValue = -num;
} else {
    absValue = num;
}
System.out.println("Absolute value: " + absValue);

Decisions: if

else-if Chains

import java.util.Scanner;

public class PositiveNegative {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        double num = scanner.nextDouble();
        if (num > 0) {
            System.out.println("Positive.");
        } else if (num < 0) {
            System.out.println("Negative.");
        } else {
            System.out.println("Zero.");
        }
    }
}
  • With more than two options, else if tests the conditions one after another.
  • Conditions are tried top to bottom; the block of the first true condition runs, and the rest are skipped.
  • If none is true, the final else runs (if present).

Three separate runs

Enter a number: 4
Positive.
Enter a number: -2
Negative.
Enter a number: 0
Zero.

Decisions: if · Step-by-step code trace

else-if Chain: Letter Grade

grade = 75grade ≥ 90 ?Print Agrade ≥ 80 ?Print Bgrade ≥ 70 ?Print Cgrade ≥ 60 ?Print DPrint FEndYNYNYNYN

grade = 75.

grade = 75grade ≥ 90 ?Print Agrade ≥ 80 ?Print Bgrade ≥ 70 ?Print Cgrade ≥ 60 ?Print DPrint FEndYNYNYNYN

75 >= 90 → false. On to the next else if.

grade = 75grade ≥ 90 ?Print Agrade ≥ 80 ?Print Bgrade ≥ 70 ?Print Cgrade ≥ 60 ?Print DPrint FEndYNYNYNYN

75 >= 80 → false. On to the next condition.

grade = 75grade ≥ 90 ?Print Agrade ≥ 80 ?Print Bgrade ≥ 70 ?Print Cgrade ≥ 60 ?Print DPrint FEndYNYNYNYN

75 >= 70 → true: the first true condition is found.

grade = 75grade ≥ 90 ?Print Agrade ≥ 80 ?Print Bgrade ≥ 70 ?Print Cgrade ≥ 60 ?Print DPrint FEndYNYNYNYN

“C” is printed.

grade = 75grade ≥ 90 ?Print Agrade ≥ 80 ?Print Bgrade ≥ 70 ?Print Cgrade ≥ 60 ?Print DPrint FEndYNYNYNYN

The remaining conditions (including grade >= 60) are never tested. Order matters: if >= 60 were at the top, 75 would get a “D”.

int grade = 75;
if (grade >= 90) {
    System.out.println("A");
} else if (grade >= 80) {
    System.out.println("B");
} else if (grade >= 70) {
    System.out.println("C");
} else if (grade >= 60) {
    System.out.println("D");
} else {
    System.out.println("F");
}

Decisions: if

Nested Decisions

  • Inside the block of one decision you can place another decision.
  • Useful for more complex conditions: once the outer condition holds, a second question is asked.
  • The inner if is tested only if the outer condition is true.
  • Deep nesting hurts readability; indent properly and, where possible, flatten with && or else if: if (age >= 18) { if (hasLicense) … } and if (age >= 18 && hasLicense) … do the same thing.
  • Range checks are also written with &&: grade >= 60 && grade < 90; 60 <= grade < 90 does not compile.
if (cond1) {
    if (cond2) {
        // cond1 AND cond2 true
    }
} else {
    // cond1 false
}
cond1?truefalsecond2?else blocktruefalseboth truenothing

Decisions: if · Step-by-step code trace

Nested Decision: Letter Grade

grade = 85grade ≥ 60 ?Print Fgrade ≥ 90 ?Print APrint BEndNYYN

grade = 85.

grade = 85grade ≥ 60 ?Print Fgrade ≥ 90 ?Print APrint BEndNYYN

Outer condition: 85 >= 60 → true. Enter the outer if block.

grade = 85grade ≥ 60 ?Print Fgrade ≥ 90 ?Print APrint BEndNYYN

Inner condition: 85 >= 90 → false. Go to the inner else.

grade = 85grade ≥ 60 ?Print Fgrade ≥ 90 ?Print APrint BEndNYYN

“Letter grade: B” is printed.

grade = 85grade ≥ 60 ?Print Fgrade ≥ 90 ?Print APrint BEndNYYN

The outer else (line 9) is skipped. grade = 45 would skip the inner if entirely and print F directly.

int grade = 85;
if (grade >= 60) {
    if (grade >= 90) {
        System.out.println("Letter grade: A");
    } else {
        System.out.println("Letter grade: B");
    }
} else {
    System.out.println("Letter grade: F");
}

Decisions: if · Step-by-step code trace

Short-Circuit: Tracing the Code

variableleftrightresults1b != 0&&a / b > 2s2b == 0||++count > 0s3b == 0&&++count > 0count = 0

b = 0: a / b would cause a division-by-zero error (ArithmeticException) if evaluated. count will count whether the right-hand sides run.

variableleftrightresults1b != 0 → false&&a / b > 2s2b == 0||++count > 0s3b == 0&&++count > 0count = 0

&& first evaluates the left side: b != 0 → false.

variableleftrightresults1b != 0 → false&&skippedfalses2b == 0||++count > 0s3b == 0&&++count > 0count = 0

If the left is false, &&'s result is already false: a / b > 2 is never evaluated, so no error occurs. s1 = false.

variableleftrightresults1b != 0 → false&&skippedfalses2b == 0 → true||++count > 0s3b == 0&&++count > 0count = 0

||: left side b == 0 → true.

variableleftrightresults1b != 0 → false&&skippedfalses2b == 0 → true||skippedtrues3b == 0&&++count > 0count = 0

If the left is true, ||'s result is already true: ++count does not run, count stays 0. s2 = true.

variableleftrightresults1b != 0 → false&&skippedfalses2b == 0 → true||skippedtrues3b == 0 → true&&++count > 0count = 0

Again &&; the left side b == 0 → true. The result is not yet known.

variableleftrightresults1b != 0 → false&&skippedfalses2b == 0 → true||skippedtrues3b == 0 → true&&++count > 0 → truetruecount = 1

The right side must be evaluated: ++count → 1, 1 > 0 → true. s3 = true.

variableleftrightresults1b != 0 → false&&skippedfalses2b == 0 → true||skippedtrues3b == 0 → true&&++count > 0 → truetruecount = 1

The three results are printed: false true true.

variableleftrightresults1b != 0 → false&&skippedfalses2b == 0 → true||skippedtrues3b == 0 → true&&++count > 0 → truetruecount = 1

count = 1: only one of the three right-hand sides ran. Side effects (++) on the right of &&/|| are therefore misleading.

int a = 10, b = 0, count = 0;
boolean s1 = b != 0 && a / b > 2;
boolean s2 = b == 0 || ++count > 0;
boolean s3 = b == 0 && ++count > 0;
System.out.println(s1 + " " + s2 + " " + s3);
System.out.println("count = " + count);

Decisions: switch

The switch-case Statement

  • switch-case compares the value of a variable against a set of constant values and acts according to the match.
  • It is used to choose one path among several options.
  • When the same variable gets many == comparisons, it is tidier than an else if chain.
  • Analogy: elevator buttons. The floor number you press picks where you go.
switch (variable) {  // value being checked
    case value1:     // one value per case
        // statements 1
        break;
    case value2:
        // statements 2
        break;
    // ...
    default:         // if nothing matches
        // default statements (optional)
}

Decisions: switch

How switch-case Works

  • The variable is compared with the case values top to bottom.
  • If a matching case is found, that case's statements run, and then break exits the switch.
  • If no case matches, the default section (if any) runs.
  • default absent as well? Then the switch exits without doing anything.
  • break missing? Execution falls into the next case (fall-through).
switch (variable)= value1 ?statements 1= value2 ?statements 2default statementsafter the switchYNYNbreak

Decisions: switch · Step-by-step code trace

Example: Finding the Season

3 4 5→ Spring6 7 8→ Summer9 10 11→ Autumn12 1 2→ Winterdefault→ Unknown

month = 4.

3 4 5→ Spring6 7 8→ Summer9 10 11→ Autumn12 1 2→ Winterdefault→ Unknown

season is declared, with no value yet.

3 4 5→ Spring6 7 8→ Summer9 10 11→ Autumn12 1 2→ Winterdefault→ Unknown

switch (month): the value 4 is computed once, then the case labels are searched.

3 4 5→ Spring6 7 8→ Summer9 10 11→ Autumn12 1 2→ Winterdefault→ Unknown

case 4 matches. The three case labels on that line lead to the same code.

3 4 5→ Spring6 7 8→ Summer9 10 11→ Autumn12 1 2→ Winterdefault→ Unknown

season = "Spring".

3 4 5→ Spring6 7 8→ Summer9 10 11→ Autumn12 1 2→ Winterdefault→ Unknown

break: switch ends; execution jumps past its closing brace (line 18).

3 4 5→ Spring6 7 8→ Summer9 10 11→ Autumn12 1 2→ Winterdefault→ Unknown

default guarantees that season gets a value on every path; without it: variable season might not have been initialized.

int month = 4;
String season;
switch (month) {
    case 3: case 4: case 5:
        season = "Spring";
        break;
    case 6: case 7: case 8:
        season = "Summer";
        break;
    case 9: case 10: case 11:
        season = "Autumn";
        break;
    case 12: case 1: case 2:
        season = "Winter";
        break;
    default:
        season = "Unknown";
}
System.out.println(month + ": " + season);

Decisions: switch · Step-by-step code trace

Forgetting break: Fall-Through

case 1:Mondaycase 2:Tuesdaycase 3:Wednesday · breakdefault:Other day

day = 2.

case 1:Mondaycase 2:Tuesdaycase 3:Wednesday · breakdefault:Other day

The case matching 2 is searched for.

case 1:Mondaycase 2:Tuesdaycase 3:Wednesday · breakdefault:Other day

case 1 is skipped, case 2 matches.

case 1:Mondaycase 2:Tuesdaycase 3:Wednesday · breakdefault:Other day

“Tuesday” is printed. There is no break here!

case 1:Mondaycase 2:Tuesdaycase 3:Wednesday · breakdefault:Other day

The case 3: label is not a test; execution falls through to the code below.

case 1:Mondaycase 2:Tuesdaycase 3:Wednesday · breakdefault:Other day

“Wednesday” is printed too, even though the day is not 3.

case 1:Mondaycase 2:Tuesdaycase 3:Wednesday · breakdefault:Other day

break exits the switch; default does not run.

case 1:Mondaycase 2:Tuesdaycase 3:Wednesday · breakdefault:Other day

Execution continues after the switch. To avoid fall-through, end every case with break.

int day = 2;
switch (day) {
    case 1:
        System.out.println("Monday");
    case 2:
        System.out.println("Tuesday");
    case 3:
        System.out.println("Wednesday");
        break;
    default:
        System.out.println("Other day");
}
System.out.println("switch done");

Decisions: switch

switch: char and String

char-based simple calculator

int a = 12, b = 4;
char op = '*';
int result;
switch (op) {
    case '+':  result = a + b;  break;
    case '-':  result = a - b;  break;
    case '*':  result = a * b;  break;
    case '/':  result = a / b;  break;
    default:
        System.out.println("Bad operator");
        result = 0;
}
System.out.println(a + " " + op + " " + b
        + " = " + result);
12 * 4 = 48

String-based command selection (Java 7+)

String command = "stop";
switch (command) {
    case "start":
        System.out.println("Engine started");
        break;
    case "stop":
        System.out.println("Engine stopped");
        break;
    default:
        System.out.println("Unknown command");
}
Engine stopped

Short cases can go on a single line: case '+': result = a + b; break;. String comparison is case-sensitive: "Stop" ≠ "stop".

Decisions: switch

switch Rules

  • The selector (the expression in parentheses) can be: byte, short, char, int (and their wrappers), String, enum.
  • long, float, double, boolean cannot be used with a classic switch.
  • case values must be compile-time constants (5, 'a', "stop", final constants).
  • The same value cannot appear in two cases.
  • Ranges (month >= 3 && month <= 5) or complex conditions need if-else.
double d = 2.5;
switch (d) { ... }
error: selector type double is not allowed
int b = 2;
switch (a) { case b: break; }
error: constant expression required
switch (a) { case 1: break; case 1: break; }
error: duplicate case label

Decisions: switch

switch-case vs. if-else

if-else / else ifswitch-case
What is tested?Any boolean condition: ranges, compound conditions, different variablesEquality of a single expression with constant values
FlexibilityMore flexibleOnly certain types and constant case values
With many optionsLong chains can look messyA neat, readable list
PitfallConditions in the wrong order pick the wrong branchbreak missing → falls into the cases below
Exampleif (grade >= 90) … else if (grade >= 80) …switch (month) { case 3: … }

Every switch can be written as an else if chain; the reverse is not always possible (e.g. ranges like grade >= 90).

Decisions: switch

The New switch (Java 14+)

int month = 11;
String season = switch (month) {
    case 3, 4, 5 -> "Spring";
    case 6, 7, 8 -> "Summer";
    case 9, 10, 11 -> "Autumn";
    case 12, 1, 2 -> "Winter";
    default -> "Unknown";
};
System.out.println(season);
Autumn
  • Java 14 introduced the arrow form: case 3, 4, 5 -> …
  • A case can take several values separated by commas.
  • The arrow form has no fall-through; no break is needed.
  • A switch expression produces a value that can be assigned directly; it ends with ;.
  • The expression form must cover every possibility: for int, default is required.
  • This course uses the classic form; the arrow form is available from Java 14 on.

Application: Temperature

Temperature Conversion: Table and Formulas

Celsius (°C)Fahrenheit (°F)Kelvin (K)
−40−40233.15
032273.15
2577298.15
100212373.15
°C−40025100°F−403277212K233.15273.15298.15373.15
Celsius → Fahrenheit

°F = (°C × 1.8) + 32

Fahrenheit → Celsius

°C = (°F − 32) / 1.8

Celsius → Kelvin

K = °C + 273.15

Goal: translate the formulas into Java and compute them for one value.

Application: Temperature

Temperature Conversion: One Value

public class Program {
    public static void main(String[] args) {
        double celsius = 25.0;
        double fahrenheit = (celsius * 1.8) + 32;
        double kelvin = celsius + 273.15;
        System.out.println(celsius + " °C = " + fahrenheit + " °F = " + kelvin + " K");
    }
}
25.0 °C = 77.0 °F = 298.15 K
  • A sequential program: three lines of computation, one line of output; no decisions or loops.
  • Use double for decimal values. Parentheses make the order explicit: first celsius * 1.8, then + 32.
  • + used with a string performs concatenation; double values print as 25.0.
  • Every computed value should be used: had kelvin not been printed, computing it would have been wasted.

Loops

Loops and Their Kinds

A loop repeats the same operation several times. Analogy: running 10 laps on a track; every lap has the same moves, and the lap counter goes up by one.

for

When the number of repetitions is known; works over a range of values.

for (int i = 0; i < 5; i++) { … }

while

Runs while a condition holds; the number of repetitions may not be known in advance.

while (condition) { … }

do-while

The condition comes last; the body runs at least once.

do { … } while (condition);

for / whileconditionbodydo-whilebodycondition0 or more passes1 or more passes
  • Loops are handy for processing a data set in order and for repeating work; they matter especially with arrays and lists.
  • One loop instead of writing the same line 100 times: the code becomes shorter, tidier and more readable.

Loops

The for Loop

for (int i = 0① initonce, at the start;i < 5② conditionbefore every pass;i++③ updateat the end of every pass) {// ④ body: the repeated work}
  • The header sets the loop's init, condition and update (increment) steps on one line, separated by ;.
  • The condition is checked before every pass (iteration); the update step changes the loop variable.
  • Order of execution: 1 → 2 → 4 → 3 → 2 → 4 → 3 → … → 2 false → exit the loop.
  • i = 0, 1, 2, 3, 4: the body runs 5 times; i reaching 5 makes the condition false. i exists only inside the loop.

Loops

How Loops Work

  • The loop starts with the init step.
  • The condition is checked.
    • If it holds, the statements in the loop body run.
    • The update (increment) step is applied (for loops).
    • If the condition still holds, the body runs again.
  • When the condition fails, the loop exits and execution continues with the next statement.
  • If the condition is false on the first check, the body never runs.
initcondition?bodyupdateafter the loopYN

1. Init: the loop variable gets its first value (once).

initcondition?bodyupdateafter the loopYN

2. The condition is checked.

initcondition?bodyupdateafter the loopYN

3. If the condition is true, the body runs.

initcondition?bodyupdateafter the loopYN

4. Update: the loop variable changes.

initcondition?bodyupdateafter the loopYN

5. Back to the condition; steps 3–4–5 repeat while it is true.

initcondition?bodyupdateafter the loopYN

6. When the condition is false, the loop exits.

Loops · Step-by-step code trace

Summing Numbers (for)

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

sum starts at 0 (the identity element of addition).

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

Init: count = 1 (once).

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

Condition: 1 <= 10 → true.

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

Pass 1: sum = 0 + 1 = 1.

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

count++ → 2, condition: 2 <= 10 → true.

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

Pass 2: sum = 1 + 2 = 3.

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

count++ → 3, condition: 3 <= 10 → true.

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

Pass 3: sum = 3 + 3 = 6. The update and condition repeat the same way on every pass.

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

Pass 4: sum = 6 + 4 = 10.

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

Pass 5: sum = 10 + 5 = 15.

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

Pass 6: sum = 15 + 6 = 21.

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

Pass 7: sum = 21 + 7 = 28.

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

Pass 8: sum = 28 + 8 = 36.

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

Pass 9: sum = 36 + 9 = 45.

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

Pass 10: sum = 45 + 10 = 55.

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

count++ → 11, condition: 11 <= 10 → false. The loop ends; the body ran exactly 10 times.

sum = 0count = 1count ≤ 10 ?sum += countcount++Print sumYN

After the loop, sum is printed. count no longer exists: it lives only inside the loop.

int sum = 0;
for (int count = 1; count <= 10; count++) {
    sum += count;
}
System.out.println("Sum: " + sum);

Loops

Summing a Range

import java.util.Scanner;

public class RangeSum {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Start value (a): ");
        int a = input.nextInt();
        System.out.print("End value (b): ");
        int b = input.nextInt();
        int sum = 0;
        for (int i = a; i <= b; i++) {
            sum += i;
        }
        System.out.println("Sum of the numbers: " + sum);
    }
}

Inputs: 3 and 7

Start value (a): 3
End value (b): 7
Sum of the numbers: 25

The loop variable i starts not at a fixed number but at the user's input a: 3 + 4 + 5 + 6 + 7 = 25.

Inputs: 7 and 3

Start value (a): 7
End value (b): 3
Sum of the numbers: 0

On the first check 7 <= 3 is false: the body never runs, and the sum stays 0. Fix: if a > b, swap the two first (with an if).

Loops

The while Loop

int i = 0;
while (i < 5) {
    // statements in the loop
    i++;
}
  • Only a condition is checked; init and update are written separately, outside and inside the loop.
  • Runs as long as the condition holds; the condition is tested before the body.
  • The natural choice when the number of repetitions isn't known in advance (e.g. “until the user enters 0”).
  • Beware of infinite loops! i++ missing → i stays 0, the condition stays true and the program never ends.
initcondition?bodyupdateafter the loopYN

Loops

for vs. while

for

int sum = 0;
for (int count = 1; count <= 10; count++) {
    sum += count;
}
System.out.println("Sum: " + sum);

while

int sum = 0;
int count = 1;
while (count <= 10) {
    sum += count;
    count++;
}
System.out.println("Sum: " + sum);
Sum: 55

Both loops have the same three parts: init count = 1, condition count <= 10, update count++. for puts them on one line; while scatters them, and the update is easy to forget. Both print 55.

Loops · Step-by-step code trace

Computing a Factorial (while)

5! = 1 × 2 × 3 × 4 × 5

Goal: 5! = 1 × 2 × 3 × 4 × 5. The product starts at 1 (if it were 0, the result would always be 0).

factorial = 1 × 1 = 1

1 <= 5 → true. factorial *= count: 1 × 1 = 1.

count = 2

count++ → 2. Back to the condition.

factorial = 1 × 2 = 2

2 <= 5 → true. factorial *= count: 1 × 2 = 2.

factorial = 2 × 3 = 6

3 <= 5 → true. factorial *= count: 2 × 3 = 6.

factorial = 6 × 4 = 24

4 <= 5 → true. factorial *= count: 6 × 4 = 24.

factorial = 24 × 5 = 120

5 <= 5 → true. factorial *= count: 24 × 5 = 120.

count = 6

count++ → 6. Back to the condition.

6 <= 5 → false

The condition is false: the loop exits.

5! = 120

The result is printed. int is enough up to 12!; 13! overflows, so long is needed.

int n = 5;
int factorial = 1;
int count = 1;
while (count <= n) {
    factorial *= count;
    count++;
}
System.out.println(n + " factorial: " + factorial);

Loops

Computing Powers (for)

import java.util.Scanner;

public class Power {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter base and exponent: ");
        int base = sc.nextInt();
        int exp = sc.nextInt();
        long result = 1;
        for (int i = 1; i <= exp; i++) {
            result = result * base;
        }
        System.out.println("Result: " + result);
        System.out.println("Math.pow: " + Math.pow(base, exp));
        sc.close();
    }
}
Enter base and exponent: 3 4
Result: 81
Math.pow: 81.0

Java's built-in Math.pow(base, exp) method does the same job but returns a double (81.0). Our own loop shows how the algorithm works; real programs prefer the library methods.

Loops

The do-while Loop

int i = 0;
do {
    // statements in the loop
    i++;
} while (i < 5);
  • Does the work first, then checks the condition.
  • Repeats while the condition holds.
  • The body runs at least once.
  • while (condition) must be followed by a semicolon.
  • Typical uses: asking again until the user gives a valid value; menus.
bodyupdatecondition?YN

Loops

do-while: Input Validation

import java.util.Scanner;

public class DoWhileInput {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int num;
        do {
            System.out.print("Enter a number (1-10): ");
            num = input.nextInt();
        } while (num < 1 || num > 10);
        System.out.println("Accepted number: " + num);
    }
}

Inputs: 15, 0, 7

Enter a number (1-10): 15
Enter a number (1-10): 0
Enter a number (1-10): 7
Accepted number: 7
  • The question must be asked at least once: do-while is made exactly for this.
  • 15 and 0 are out of range: the condition num < 1 || num > 10 is true → ask again.
  • 7 is valid: the condition is false → exit the loop.
  • num is declared before the loop because it is used in the condition and after the loop.

Loops · Step-by-step code trace

Input Validation: Tracing the Code

keyboard input12-34

The user will type 12, −3, 4 in turn. num is declared before the loop; it is used in the condition and after the loop.

keyboard input12-34num = 12

The question is asked without checking the condition. nextInt() reads the first input: num = 12.

keyboard input12-34num = 1212 < 1 || 12 > 10 → trueask again

12 < 1 || 12 > 10: the right side is true → the condition is true, so the question is asked again.

keyboard input12-34num = -3

The second input is read: num = -3.

keyboard input12-34num = -3-3 < 1 || -3 > 10 → trueask again

-3 < 1 is true; || skips the right side → the condition is true, again.

keyboard input12-34num = 4

Third input: num = 4.

keyboard input12-34num = 44 < 1 || 4 > 10 → falseexit

4 < 1 false, 4 > 10 false → the condition is false: the loop exits.

keyboard input12-34num = 4

The valid number is accepted. The question was asked 3 times; the loop runs until a valid number arrives.

Scanner input = new Scanner(System.in);
int num;
do {
    System.out.print("Enter a number (1-10): ");
    num = input.nextInt();
} while (num < 1 || num > 10);
System.out.println("Accepted number: " + num);

Loops · Step-by-step code trace

while vs. do-while

i = 10

i = 10.

i < 5 → 10 < 5 → false

while tests its condition first: false. The body (lines 3–4) never runs.

j = 10

j = 10.

do: enter without checking

The do block is entered with no check.

do-while: 10

The body runs once.

j = 11

j++ → 11.

j < 5 → 11 < 5 → false

The condition is then tested: false → exit.

while: 0 passes · do-while: 1 pass

Same condition, different result: while ran 0 times, do-while ran once.

int i = 10;
while (i < 5) {
    System.out.println("while: " + i);
    i++;
}
int j = 10;
do {
    System.out.println("do-while: " + j);
    j++;
} while (j < 5);
System.out.println("i = " + i + ", j = " + j);

Loops

Comparing the Loop Types

forwhiledo-while
Where is the condition tested?Before every passBefore every passAfter every pass
Minimum passes?001
Init / updateIn the header, on one lineOutside the loop / in the bodyOutside the loop / in the body
When?Known count: “from 1 to n”, “every element of an array”Until a condition changes: “until the number is 0”The work must happen at least once: input validation, menus
Syntaxfor (init; cond; upd) { }while (cond) { }do { } while (cond);

The three loops can be converted into one another; choose for readability.

Loops

The for Loop: Playground

The boxes show the value of i on each pass the body ran. Try: init 10, condition <=, end 1 (never runs); update i-- with <= (infinite loop); init 1, != and i += 2 with end 9 (stops) and 10 (never equal: infinite). The simulation stops after 200 passes.

Nested Loops

Nested Loops

  • A nested loop is a loop inside the body of another loop.
  • Used for more complex work: matrices and multidimensional arrays, tables, patterns.
  • Analogy: a clock. Each time the hour hand (outer loop) moves one step, the minute hand (inner loop) goes all the way round.
  • The total number of passes is a product: 3 outer × 2 inner = 6 runs of the body.
  • The number of nested loops and their conditions affect complexity. Too much nesting leads to complex, slow code: three loops × 1000 passes = 1 billion operations!
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        // nested loop body
    }
}
j = 1j = 2i = 11,11,2i = 22,12,2i = 33,13,2

Nested Loops · Step-by-step code trace

How Nested Loops Work

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

Outer loop starts: i = 1, 1 <= 3 → true.

j = 1j = 2i = 11,1i = 2i = 3

Inner loop starts: j = 1. Body: i = 1, j = 1 is printed.

j = 1j = 2i = 11,11,2i = 2i = 3

Body: i = 1, j = 2 is printed.

j = 1j = 2i = 11,11,2i = 2i = 3

j = 3 → 3 <= 2 false: the inner loop is done. Back to the outer loop: i++ → 2, 2 <= 3 → true; the inner loop starts over.

j = 1j = 2i = 11,11,2i = 22,1i = 3

Inner loop starts: j = 1. Body: i = 2, j = 1 is printed.

j = 1j = 2i = 11,11,2i = 22,12,2i = 3

Body: i = 2, j = 2 is printed.

j = 1j = 2i = 11,11,2i = 22,12,2i = 3

j = 3 → 3 <= 2 false: the inner loop is done. Back to the outer loop: i++ → 3, 3 <= 3 → true; the inner loop starts over.

j = 1j = 2i = 11,11,2i = 22,12,2i = 33,1

Inner loop starts: j = 1. Body: i = 3, j = 1 is printed.

j = 1j = 2i = 11,11,2i = 22,12,2i = 33,13,2

Body: i = 3, j = 2 is printed.

j = 1j = 2i = 11,11,2i = 22,12,2i = 33,13,2

j = 3 → 3 <= 2 false: the inner loop is done. i++ → 4, 4 <= 3 false: the outer loop ends too. The body ran 3 × 2 = 6 times.

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        System.out.println("i = " + i + ", j = " + j);
    }
}

Nested Loops · Step-by-step code trace

Example: Star Pattern

The inner loop's bound depends on the outer loop's variable (j <= i): each row prints one more star.

j = 1j = 2j = 3j = 4i = 1*i = 2i = 3i = 4

Row 1: the inner loop runs j from 1 to i = 1. print("* "): stays on the same line.

j = 1j = 2j = 3j = 4i = 1*i = 2i = 3i = 4

Inner loop done (j = 2 > 1). println() moves to the next line.

j = 1j = 2j = 3j = 4i = 1*i = 2*i = 3i = 4

Row 2: the inner loop runs j from 1 to i = 2. print("* "): stays on the same line.

j = 1j = 2j = 3j = 4i = 1*i = 2**i = 3i = 4

print("* "): stays on the same line.

j = 1j = 2j = 3j = 4i = 1*i = 2**i = 3i = 4

Inner loop done (j = 3 > 2). println() moves to the next line.

j = 1j = 2j = 3j = 4i = 1*i = 2**i = 3*i = 4

Row 3: the inner loop runs j from 1 to i = 3. print("* "): stays on the same line.

j = 1j = 2j = 3j = 4i = 1*i = 2**i = 3**i = 4

print("* "): stays on the same line.

j = 1j = 2j = 3j = 4i = 1*i = 2**i = 3***i = 4

print("* "): stays on the same line.

j = 1j = 2j = 3j = 4i = 1*i = 2**i = 3***i = 4

Inner loop done (j = 4 > 3). println() moves to the next line.

j = 1j = 2j = 3j = 4i = 1*i = 2**i = 3***i = 4*

Row 4: the inner loop runs j from 1 to i = 4. print("* "): stays on the same line.

j = 1j = 2j = 3j = 4i = 1*i = 2**i = 3***i = 4**

print("* "): stays on the same line.

j = 1j = 2j = 3j = 4i = 1*i = 2**i = 3***i = 4***

print("* "): stays on the same line.

j = 1j = 2j = 3j = 4i = 1*i = 2**i = 3***i = 4****

print("* "): stays on the same line.

j = 1j = 2j = 3j = 4i = 1*i = 2**i = 3***i = 4****

Inner loop done (j = 5 > 4). println() moves to the next line. 1 + 2 + 3 + 4 = 10 stars in total.

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

Nested Loops

Place Value: What Is Printed?

for (int tens = 0; tens <= 4; tens++) {
    for (int ones = 1; ones <= 9; ones++) {
        int num = tens * 10 + ones;
        System.out.println("Tens digit: " + tens
                + ", ones digit: " + ones + " --> " + num);
    }
}

Question: how many lines does the program print? What are the first and last lines? Which numbers are never printed?

Answer
Tens digit: 0, ones digit: 1 --> 1
Tens digit: 0, ones digit: 2 --> 2
Tens digit: 0, ones digit: 3 --> 3
…
Tens digit: 4, ones digit: 8 --> 48
Tens digit: 4, ones digit: 9 --> 49

The outer loop runs 5 times (tens = 0…4), the inner loop 9 times (ones = 1…9): 5 × 9 = 45 lines. num = 1…49; ones doesn't start at 0, so 10, 20, 30, 40 are never printed. A long string is split across two lines with +; a line break inside the quotes gives an unclosed string literal error.

Nested Loops

Multiplication Table

for (int i = 1; i <= 10; i++) {
    for (int j = 1; j <= 10; j++) {
        int product = i * j;
        System.out.print(i + "x" + j + "=" + product + "\t");
    }
    System.out.println(); // new line
}
  • The outer loop walks the rows (i), the inner one the columns (j): 10 × 10 = 100 products.
  • print stays on the line; "\t" (tab) aligns columns.
  • println() then starts a new row: outside the inner loop, inside the outer one.
j=1j=2j=3j=4i=11234i=22468i=336912i=4481216inner loop: j = 1…10

Excerpt of the output (tabs shown as spaces)

1x1=1   1x2=2   1x3=3   1x4=4   1x5=5   1x6=6   …
2x1=2   2x2=4   2x3=6   2x4=8   2x5=10   2x6=12   …
3x1=3   3x2=6   3x3=9   3x4=12   3x5=15   3x6=18   …
…
10x1=10   10x2=20   10x3=30   10x4=40   10x5=50   …

break and continue · Step-by-step code trace

break in Loops

break is used to end a loop: once its condition holds, execution leaves the loop.

12345678910i

i = 1: 1 == 5 false, break is skipped; the step is printed.

1✓2345678910i

i = 2: 2 == 5 false → printed.

1✓2✓345678910i

i = 3: 3 == 5 false → printed.

1✓2✓3✓45678910i

i = 4: 4 == 5 false → printed.

1✓2✓3✓4✓5stop678910i

i = 5: condition true → break. The loop ends immediately; 5 is not printed and 6–10 are never tried.

1✓2✓3✓4✓5stop678910i

Statements after the loop continue. i no longer exists.

for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break;
    }
    System.out.println("Loop step: " + i);
}
System.out.println("Left the loop.");

break and continue

Prime Check: A Flag and break

import java.util.Scanner;

public class PrimeCheck {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();
        boolean isPrime = true;            // flag
        if (num < 2) isPrime = false;     // 0 and 1 are not prime
        for (int divisor = 2; divisor <= num / 2; divisor++) {
            if (num % divisor == 0) {      // divides evenly
                isPrime = false;
                break;                    // break out of the loop
            }
        }
        if (isPrime) {
            System.out.println(num + " is prime.");
        } else {
            System.out.println(num + " is not prime.");
        }
        sc.close();
    }
}
Enter a number: 21
21 is not prime.

Enter a number: 97
97 is prime.

Faster: if a number has a divisor, one of them is at most √num. With the condition divisor * divisor <= num, only 8 divisors are tried for 97 instead of 47.

break and continue · Step-by-step code trace

continue in Loops

continue skips the rest of the current pass and moves on to the next pass.

12345678910i

i = 1 is odd → condition false, the number is printed.

1✓2345678910i

i = 2 is even → continue: line 5 is skipped; control goes straight to i++.

1✓2skip345678910i

i = 3 is odd → condition false, the number is printed.

1✓2skip3✓45678910i

i = 4 is even → continue: line 5 is skipped; control goes straight to i++.

1✓2skip3✓4skip5678910i

i = 5 is odd → condition false, the number is printed.

1✓2skip3✓4skip5✓678910i

i = 6 is even → continue: line 5 is skipped; control goes straight to i++.

1✓2skip3✓4skip5✓6skip78910i

i = 7 is odd → condition false, the number is printed.

1✓2skip3✓4skip5✓6skip7✓8910i

i = 8 is even → continue: line 5 is skipped; control goes straight to i++.

1✓2skip3✓4skip5✓6skip7✓8skip910i

i = 9 is odd → condition false, the number is printed.

1✓2skip3✓4skip5✓6skip7✓8skip9✓10i

i = 10 is even → continue: line 5 is skipped; control goes straight to i++.

1✓2skip3✓4skip5✓6skip7✓8skip9✓10skipi

11 <= 10 false: the loop ends normally. continue does not end the loop; it only skips that pass.

for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;
    }
    System.out.println("Odd number: " + i);
}

break and continue

break vs. continue

break: ends the loopi = 1i ≤ 10 ?i == 5 ?breakPrint ii++afterYNNY

The loop ends completely; execution moves to the statement after the loop.

continue: skips a passi = 1i ≤ 10 ?i even?continuePrint ii++afterYNNY

The rest of the pass is skipped; the loop goes on with the update and the condition.

Both are usually used inside an if; they also work in while and do-while; in while, a continue that skips the update can cause an infinite loop.

break and continue

break in Nested Loops

break ends only the inner loop

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

Labeled break: leaving the outer loop

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

In the left example, for each i only j = 1 is printed and the outer loop goes on. On the right, the outer: label names the outer loop; when i * j == 4 (i = 2, j = 2) break outer; exits both loops at once. Use labels sparingly.

break and continue · Step-by-step code trace

Labeled break: Tracing the Code

j = 1j = 2j = 3i = 11 × 11 × 21 × 3i = 22 × 12 × 22 × 3i = 33 × 13 × 23 × 3

The outer: label names the outer loop. i = 1, j = 1: 1 × 1 = 1 ≠ 4, printed.

j = 1j = 2j = 3i = 11 × 11 × 21 × 3i = 22 × 12 × 22 × 3i = 33 × 13 × 23 × 3

j = 2: 1 × 2 = 2, printed.

j = 1j = 2j = 3i = 11 × 11 × 21 × 3i = 22 × 12 × 22 × 3i = 33 × 13 × 23 × 3

j = 3: 1 × 3 = 3, printed. The inner loop ends; the outer loop moves to i = 2.

j = 1j = 2j = 3i = 11 × 11 × 21 × 3i = 22 × 12 × 22 × 3i = 33 × 13 × 23 × 3

i = 2, j = 1: 2 × 1 = 2, printed.

j = 1j = 2j = 3i = 11 × 11 × 21 × 3i = 22 × 12 × 22 × 3i = 33 × 13 × 23 × 3

i = 2, j = 2: 2 × 2 = 4 → the condition is true.

j = 1j = 2j = 3i = 11 × 11 × 21 × 3i = 22 × 12 × 22 × 3i = 33 × 13 × 23 × 3break outer → leaves both loops

break outer; exits not just the inner loop but the labeled outer loop too. The remaining cells are never visited.

j = 1j = 2j = 3i = 11 × 11 × 21 × 3i = 22 × 12 × 22 × 3i = 33 × 13 × 23 × 3break outer → leaves both loops

Flow jumps past both loops: done is printed. With an unlabeled break, the i = 3 pass would run too.

outer:
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (i * j == 4) {
            break outer;
        }
        System.out.println(i + " x " + j);
    }
}
System.out.println("done");

Summary

Summary

StructureWhat it doesSyntax
SequentialStatements run top to bottom, once each—
if / elseIf the condition is true one block, otherwise the otherif (c) { } else { }
else ifThe block of the first true condition runsif (c1) { } else if (c2) { } else { }
switchCompares a value with constant cases; exits with breakswitch (x) { case 1: … break; default: … }
forInit, condition and update on one line; counted repetitionfor (int i = 0; i < n; i++) { }
whileWhile the condition is true; 0 or more passeswhile (c) { }
do-whileBody first, then the condition; at least 1 passdo { } while (c);
break / continueEnds the loop / skips the passbreak; · continue;

Summary

Common Mistakes: Decisions

Comparing with =if (x = 5) → error: incompatible types: int cannot be converted to boolean. Correct: x == 5.
Semicolon after ifif (x > 5); { … } compiles, but the ; is an empty statement: the block always runs.
Blockless bodyif (c) a(); b(); else c(); → error: 'else' without 'if'. Braces { } are required for more than one statement.
Forgetting breakswitch: with no break, the cases below run too (fall-through). The compiler doesn't warn you.
Assigning without defaultIf the variable is assigned only in the cases: error: variable season might not have been initialized. Fix: add a default.
Dot in decimal inputWith a Turkish locale, nextDouble() given -7.5 → InputMismatchException. -7,5 is what you must type.

Summary

Common Mistakes: Loops

Infinite loopwhile: forgetting the update (i++) or updating in the wrong direction (i-- with i <= 10). The compiler won't catch it; the program never stops.
; in the loop headerfor (int i = 0; i < 3; i++); or while (i < 5); is a loop with an empty body; the block below doesn't belong to it.
Off-by-one errorFor “from 1 to 10”, writing i < 10 skips 10; i = 0 with i <= 10 runs 11 times. Check the first and last pass separately.
Using the loop variable outsidefor (int i …) { } followed by println(i) → error: cannot find symbol. If needed, declare i before the loop.
Code after breakbreak; System.out.println(i); → error: unreachable statement. break: the line after it can never be reached.
Sum/product initial valueA sum starts at 0, a product at 1. factorial = 0 makes the result always 0. Resetting the variable inside the loop is wrong too.

Summary

Practice Problems (1): What Is Printed?

Problem 1

int x = 7;
if (x > 5)
    if (x > 10)
        System.out.println("A");
    else
        System.out.println("B");

Problem 2

int s = 0;
for (int i = 1; i <= 10; i += 3) {
    s += i;
}
System.out.println(s);

Problem 3

int k = 2;
int points = 0;
switch (k) {
    case 1:  points += 10;
    case 2:  points += 20;
    case 3:  points += 30;  break;
    case 4:  points += 40;
}
System.out.println(points);
Answers
  1. B. else goes with the nearest if (the inner one): 7 > 5 is true, 7 > 10 is false → B.
  2. 22. i = 1, 4, 7, 10; sum 22.
  3. 50. case 2 is entered (+20), break is missing: case 3 is reached by fall-through (+30). Total 50.

Summary

Practice Problems (2)

Problem 4

Write code that sums the numbers from 1 to 100 that are divisible by 3 or 5.

Problem 5

Find how many digits an integer (e.g. 2024) has, using a while loop (num /= 10 drops the last digit).

Answers
int sum = 0;
for (int i = 1; i <= 100; i++) {
    if (i % 3 == 0 || i % 5 == 0) {
        sum += i;
    }
}
System.out.println(sum);

Output: 2418. Each number is tested once; || ensures common multiples such as 15 are not added twice.

int num = 2024, digits = 0;
while (num > 0) {
    digits++;
    num /= 10;
}
System.out.println(digits);

Output: 4. Each pass drops the last digit: 2024 → 202 → 20 → 2 → 0.

Summary

Exercises (1)

Exercise 1
int n = 1;
while (n < 100) {
    n *= 3;
}
System.out.println(n);
Exercise 2
int k = 5;
do {
    k -= 2;
} while (k > 0);
System.out.println(k);
Exercise 3
int count = 0;
for (int i = 1; i <= 4; i++) {
    for (int j = i; j <= 4; j++) {
        count++;
    }
}
System.out.println(count);
Answers (solve on paper first, then run the code to check)
  1. 243. n: 1 → 3 → 9 → 27 → 81 → 243; it stops when 243 < 100 is false.
  2. -1. k: 5 → 3 → 1 → −1. The condition is checked at the end, so it goes down to −1.
  3. 10. The inner loop runs i = 1, 2, 3, 4: 4 + 3 + 2 + 1 = 10.

Summary

Exercises (2)

Exercise 4
int t = 0;
for (int i = 1; i <= 10; i++) {
    if (i % 3 == 0) {
        continue;
    }
    t += i;
}
System.out.println(t);
Exercise 5
int i = 10;
while (i >= 1) {
    System.out.print(i + " ");
    i -= 2;
}
System.out.println();
Exercise 6
int a = 17, b = 42;
int max = (a > b) ? a : b;
System.out.println(max);
Answers
  1. 37. The sum of 1–10 is 55; the skipped 3 + 6 + 9 = 18; 55 − 18 = 37.
  2. 10 8 6 4 2. i goes down from 10 by 2; at 0, 0 >= 1 is false. for version: for (int i = 10; i >= 1; i -= 2).
  3. 42. 17 > 42 is false, so the second value is chosen. Also write the equivalent if-else.

Summary

References

  • Oracle, The Java Tutorials: “Control Flow Statements” (if-then-else, switch, while, do-while, for, branching statements).
  • J. Gosling et al., The Java Language Specification, Java SE 21 Edition (Chapter 14: Blocks, Statements, and Patterns).
  • P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Chapters 4–5: Control Statements).
  • A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly (Chapter 5: Conditionals and Logic, Chapter 6: Loops).
  • K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly.
  • C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed. (3.8: Control Flow).

The End

Chapter 3.1: Control Structures
Previous: Chapter 2.2: Syntax Rules · Next: Chapter 3.2: Methods
1 / 1 Sercan KÜLCÜ. All rights reserved.