Programming Fundamentals

Chapter 4
Selection and Iteration

Certificate in Java-Python-Programming Languages
Programming Fundamentals   •   Certificate

Selection and Iteration

Introduction

A program rarely performs the same operation for every possible input. It may need to choose one action when a condition is true and another when it is false. It may also need to repeat a task until a condition changes or until every item in a collection has been processed. These capabilities are provided by control-flow statements.

Selection and iteration are central to programming because they allow algorithms to respond to data, enforce rules, validate input, and automate repetitive work. In Java and Python, the main selection tools are if, else if/elif, else, and multi-branch constructs such as Java switch and Python match. The principal iteration tools are for and while loops. These can be combined through nesting and controlled with break, continue, and, in Python, pass.

This chapter develops the reasoning required to design reliable control flow rather than merely memorizing syntax.

Learning Objectives

By the end of this chapter, you should be able to:

  • represent decisions using Boolean expressions;
  • write and trace if/else structures in Java and Python;
  • select among several alternatives using switch or match-style logic;
  • choose appropriately between for and while loops;
  • construct nested decisions and loops safely;
  • validate input using conditions and repetition;
  • use break and continue appropriately;
  • identify common control-flow errors and improve code readability;
  • design a small program that combines selection, iteration, and validation.

1. Boolean Logic: The Foundation of Control Flow

A Boolean expression evaluates to one of two logical values: true or false. In Java these values are true and false; in Python they are True and False.

Common comparison operators are shown below.

MeaningJava and Python notationExample
Equal to==age == 18
Not equal to!=status != "closed"
Less than<score < 50
Greater than>temperature > 30
Less than or equal to<=attempts <= 3
Greater than or equal to>=balance >= 0

Assignment is not comparison. The statement x = 5 stores a value, whereas x == 5 tests a condition. Confusing these operations is a frequent source of errors.

Logical Operators

Several conditions can be combined with logical operators.

MeaningJavaPython
AND&&and
OR`
NOT!not

For an AND expression, every required condition must be true. For an OR expression, at least one condition must be true. NOT reverses a Boolean value.

For example, a learner qualifies for an assessment if attendance is at least 75 percent and the fee has been paid:

eligible = attendance >= 75 and fee_paid

The equivalent Java expression is:

boolean eligible = attendance >= 75 && feePaid;

Short-Circuit Evaluation

Java and Python normally evaluate logical expressions from left to right and stop when the result is already known. This is called short-circuit evaluation. In the expression x != 0 and 100 / x > 2, the division is attempted only if x != 0 is true. This can prevent an error and can make conditions more efficient.

Conditions should be written so that potentially unsafe operations occur only after necessary checks. Short-circuiting is useful, but it should not be used to hide complicated logic. Named Boolean variables can improve clarity.

2. Conditional Selection with if and else

An if statement executes a block only when its condition is true.

Python:

if score >= 50:
    print("Pass")

Java:

if (score >= 50) {
    System.out.println("Pass");
}

Python uses indentation to define a block. Java uses braces, although consistent indentation remains essential for human readers.

An if statement may be extended with an alternative:

if balance >= price:
    print("Purchase approved")
else:
    print("Insufficient balance")
if (balance >= price) {
    System.out.println("Purchase approved");
} else {
    System.out.println("Insufficient balance");
}

Multiple Alternatives

When more than two outcomes are possible, use an elif chain in Python or an else if chain in Java.

if mark >= 70:
    grade = "A"
elif mark >= 60:
    grade = "B"
elif mark >= 50:
    grade = "C"
else:
    grade = "F"
if (mark >= 70) {
    grade = "A";
} else if (mark >= 60) {
    grade = "B";
} else if (mark >= 50) {
    grade = "C";
} else {
    grade = "F";
}

Conditions are tested from top to bottom. Once one condition is true, its block executes and the remaining conditions are skipped. Therefore, order matters. If the test mark >= 50 appeared first, all marks of 50 or more would receive the same result and the later tests would never be reached.

Guard Conditions

A guard condition rejects invalid or exceptional cases early.

if age < 0:
    print("Invalid age")
elif age < 18:
    print("Minor")
else:
    print("Adult")

Guard conditions reduce deep nesting and make invalid states explicit.

3. Multi-Branch Selection

An if chain is flexible because it can test ranges and complex expressions. A multi-branch selection construct is often clearer when one value is compared with several fixed alternatives.

Java switch

switch (day) {
    case 1:
        name = "Monday";
        break;
    case 2:
        name = "Tuesday";
        break;
    default:
        name = "Unknown";
}

In traditional Java switch, break prevents execution from continuing into the next case. Omitting it may cause fall-through, which is sometimes intentional but often accidental. Modern Java also supports arrow-style cases:

String name = switch (day) {
    case 1 -> "Monday";
    case 2 -> "Tuesday";
    default -> "Unknown";
};

The arrow form avoids accidental fall-through and can return a value directly.

Python match

Python 3.10 and later provides match and case for structural pattern matching.

match command:
    case "start":
        print("System starting")
    case "stop":
        print("System stopping")
    case _:
        print("Unknown command")

The underscore is a wildcard pattern. Python match is more expressive than a simple equality-based switch because it can match structures and extract values. It should nevertheless be used only when it improves readability; an if chain may be clearer for ranges or unrelated conditions.

Choosing a Selection Construct

Use if when conditions involve ranges, Boolean combinations, or different variables. Use switch or match when alternatives are organized around one expression or recognizable patterns. In every case, provide a clear response for unexpected values where practical.

4. Iteration and Repetition

An iteration is one execution of a loop body. A loop repeatedly executes a block according to a controlling rule. Every sound loop requires:

  1. initialization of relevant state;
  2. a continuation condition or collection of items;
  3. progress toward termination;
  4. a body that performs the required work.

If progress is absent, a loop may never terminate. If the condition is wrong, the loop may execute too many or too few times.

for Loops

A for loop is appropriate when the program processes a known sequence or a controlled range.

Python:

for number in range(1, 6):
    print(number)

This prints 1 through 5 because the start value is included and the stop value, 6, is excluded.

Java:

for (int number = 1; number <= 5; number++) {
    System.out.println(number);
}

The Java loop has initialization, a continuation condition, and an update expression. Python commonly iterates directly over collections:

names = ["Amina", "Leo", "Ravi"]
for name in names:
    print(name)

Java’s enhanced for loop provides similar behavior:

String[] names = {"Amina", "Leo", "Ravi"};
for (String name : names) {
    System.out.println(name);
}

Direct iteration is usually clearer than manually managing an index when the index is not needed.

while Loops

A while loop is appropriate when the number of repetitions is not known in advance and continuation depends on a changing condition.

command = ""
while command != "quit":
    command = input("Enter a command: ")
while (!command.equals("quit")) {
    command = scanner.nextLine();
}

A while loop is pre-test: the condition is checked before the first iteration. Consequently, its body may execute zero times.

Java and Python also provide post-test-like behavior through a do-while loop in Java, but Python has no built-in do-while statement. The equivalent Python pattern is usually while True with a controlled break.

Java:

do {
    value = scanner.nextInt();
} while (value < 1 || value > 10);

Python:

while True:
    value = int(input("Enter 1-10: "))
    if 1 <= value <= 10:
        break

5. Validation Through Iteration

Input validation ensures that data satisfies required rules before it is used. A robust validator identifies the acceptable domain, reports the problem, and repeats until valid input is received.

while True:
    try:
        age = int(input("Enter age from 0 to 120: "))
        if 0 <= age <= 120:
            break
        print("Age is outside the permitted range.")
    except ValueError:
        print("Enter a whole number.")

This example addresses two different failures: non-numeric input and numeric input outside the permitted range. Validation should occur as close as practical to the point where data enters the program.

A validation rule can be represented as a predicate: a condition that is true for acceptable values and false for unacceptable values. For an integer age, the predicate is 0 ≤ age ≤ 120. This notation states the inclusive lower and upper bounds.

Validation is not the same as trusting a user interface. Data received from files, networks, databases, and other programs also requires validation. In professional systems, validation may include type, range, format, length, authorization, and consistency checks.

6. Nesting and Decomposition

A statement inside another selection or loop is nested. Nesting is necessary for many algorithms, such as examining every row and every column of a table.

for row in range(3):
    for column in range(4):
        print(row, column)

The inner loop completes all four iterations for each iteration of the outer loop. Therefore, the body executes 3 × 4 = 12 times. The multiplication applies because each of the three outer iterations triggers four inner iterations.

Nested selection is also common:

if logged_in:
    if is_admin:
        print("Administrative controls")
    else:
        print("Standard controls")
else:
    print("Please log in")

Deep nesting can make logic difficult to understand. Guard clauses, Boolean variables, helper functions, and early rejection can reduce complexity. A function that validates one rule should not also perform unrelated reporting, file access, and database updates unless there is a clear design reason.

7. Loop-Control Statements

break

break terminates the nearest enclosing loop immediately.

for item in items:
    if item == target:
        found = True
        break

The loop ends when the target is found. A break is appropriate when continuing would provide no additional value, such as a successful search or a user selecting an exit command.

continue

continue skips the remainder of the current iteration and begins the next iteration.

for value in values:
    if value < 0:
        continue
    total += value

This adds only non-negative values. The condition should be clear, because excessive use of continue can hide the main path of execution.

pass in Python

Python’s pass does nothing. It is a syntactic placeholder, not a loop-control operation.

if experimental_feature:
    pass
else:
    run_standard_feature()

Java has no direct equivalent because an empty block is syntactically valid.

8. Worked Example: A Menu-Driven Inventory Tool

Consider an illustrative inventory program. The user can add stock, sell stock, view the quantity, or exit. The program must reject invalid quantities and prevent sales greater than available stock.

stock = 10

while True:
    print("A. Add stock")
    print("S. Sell stock")
    print("V. View stock")
    print("Q. Quit")
    choice = input("Choose: ").strip().upper()

    if choice == "Q":
        print("Program ended")
        break
    elif choice == "V":
        print(f"Current stock: {stock}")
    elif choice in ("A", "S"):
        try:
            quantity = int(input("Quantity: "))
            if quantity <= 0:
                print("Quantity must be positive.")
            elif choice == "A":
                stock += quantity
                print("Stock added.")
            elif quantity > stock:
                print("Insufficient stock.")
            else:
                stock -= quantity
                print("Sale recorded.")
        except ValueError:
            print("Quantity must be a whole number.")
    else:
        print("Unknown menu option.")

The design includes a controlling while loop, menu selection, validation, nested decisions, and a terminating break. The invariant that stock should never be negative is protected by the condition quantity > stock before a sale is completed.

9. Applied Case: Examination Result Processing

Background

A training centre needs a small program to process marks for a class. Each mark must be between 0 and 100. The program should classify each valid mark as distinction, pass, or fail and should report the class average.

Problem

The system must reject invalid marks, process an unknown number of entries, stop when the user enters -1, and avoid including the sentinel in the average.

Approach

The sentinel-controlled loop below maintains total and count. The sentinel is checked before validation because -1 means “finish,” not “invalid mark to be reported.”

total = 0
count = 0

while True:
    try:
        mark = int(input("Enter mark (0-100), or -1 to finish: "))
    except ValueError:
        print("Enter a whole number.")
        continue

    if mark == -1:
        break
    if mark < 0 or mark > 100:
        print("Mark must be from 0 to 100.")
        continue

    if mark >= 70:
        category = "Distinction"
    elif mark >= 50:
        category = "Pass"
    else:
        category = "Fail"

    print(category)
    total += mark
    count += 1

if count > 0:
    average = total / count
    print(f"Average: {average:.2f}")
else:
    print("No marks were entered.")

Analysis

The continue statements ensure that invalid input does not reach the classification and accumulation code. The count > 0 test prevents division by zero when the user ends the program without entering a mark. The algorithm has one principal pass through the input stream, so its time grows in proportion to the number of valid entries. It uses a fixed number of aggregate variables, so its additional memory use is constant.

Outcome and Learning Points

The case illustrates sentinel-controlled iteration, validation, mutually exclusive selection, exception handling, and safe aggregation. It also demonstrates that control-flow design should account for boundary cases such as no data, minimum values, maximum values, and invalid input.

10. Common Errors and Best Practices

Off-by-One Errors

An off-by-one error occurs when a loop executes one time too many or too few. Remember that Python’s range(start, stop) excludes stop, while a Java condition such as i <= stop includes the boundary. Test the first, last, and empty cases.

Infinite Loops

A loop may never terminate if its condition never becomes false. Check that every iteration changes the state used by the condition, or that a reachable break exists for an intentional sentinel loop.

Accidental Assignment or Comparison Errors

Use == for comparison and = for assignment. In Java, comparing object text with == compares references rather than content; use .equals() for strings. Python’s is tests object identity and should not replace == for ordinary value comparison.

Missing Braces or Incorrect Indentation

In Java, omitting braces can make only one statement conditional. In Python, incorrect indentation changes the block or causes a syntax error. Use braces consistently in Java and consistent indentation in Python.

Overly Complex Conditions

Break complicated conditions into named variables or helper functions. For example, has_valid_age and has_permission may be clearer than a long expression combining many tests.

Best Practices

  • Give conditions meaningful names.
  • Keep loop bodies short and focused.
  • Validate at boundaries.
  • Make termination conditions explicit.
  • Prefer direct collection iteration when an index is unnecessary.
  • Include a default or fallback case for unexpected selections.
  • Test empty, minimum, maximum, and invalid inputs.
  • Use comments to explain why unusual control flow exists, not what obvious syntax does.
  • Avoid deeply nested code when guard clauses or functions can clarify the design.

11. Professional and Ethical Considerations

Control flow affects safety, fairness, and security. A validation rule that is too weak may permit unsafe data; a rule that is too strict may unfairly reject legitimate users. Programs handling financial, educational, medical, or access-control decisions should make rules explicit, testable, and auditable.

Never rely solely on client-side validation when a server or database is involved. Revalidate untrusted input at the authoritative boundary. Loops that process external data should have sensible limits or timeouts where denial-of-service risk exists. Error messages should help legitimate users recover without revealing sensitive implementation details.

AI coding assistants can suggest loops and conditions, but generated code must be reviewed. Particular risks include incorrect boundary conditions, missing validation, infinite loops, and silently ignored error cases. Human developers remain responsible for testing and consequences.

Chapter Summary

Selection allows a program to choose actions based on Boolean expressions. if/else structures are flexible for ranges and compound conditions, while Java switch and Python match organize alternatives around values or patterns. Iteration repeats work through for and while loops. A reliable loop has initialization, a continuation rule, progress toward termination, and a well-defined body. Validation commonly combines a loop with conditions and exception handling. Nested structures solve multi-level problems but should be kept understandable. break exits the nearest loop, continue skips to the next iteration, and Python pass serves as a placeholder. Professional control flow requires careful boundary testing, safe handling of invalid input, clear termination, and attention to security and fairness.

Key Terms

Boolean expression: An expression that evaluates to true or false.

Condition: A Boolean rule used to control execution.

Selection: Choosing among alternative execution paths.

Iteration: One execution of a loop body.

Loop: A control structure that repeats a block of statements.

Predicate: A condition that classifies values as acceptable or unacceptable.

Short-circuit evaluation: Stopping logical evaluation once the result is known.

Guard condition: An early test that rejects an invalid or exceptional case.

Nested statement: A statement placed inside another control structure.

Sentinel: A special value that signals termination of input or repetition.

Fall-through: Continuing from one switch case into another case.

Validation: Checking that data satisfies required rules.

break: A statement that terminates the nearest loop.

continue: A statement that skips the remainder of the current iteration.

Infinite loop: A loop that does not reach a terminating condition.

Off-by-one error: A boundary error causing one extra or one missing iteration.

Invariant: A property that should remain true during program execution.

Structural pattern matching: Matching data against patterns, as supported by Python match.

Review Questions

Short Answer Questions

  1. What is the difference between assignment and comparison?
  2. Why does the order of conditions in an if/elif chain matter?
  3. When is a while loop generally preferable to a for loop?
  4. What is the purpose of a sentinel value?
  5. What does continue do inside a loop?

Long Answer Questions

  1. Explain Boolean AND, OR, and NOT operations and give a programming example of each.
  2. Compare Java switch with Python match and an if/else chain.
  3. Describe the four design requirements of a reliable loop.
  4. Explain how input validation can combine conditions, repetition, and exception handling.
  5. Discuss the benefits and risks of nested control structures.

Analytical / Application Questions

  1. Design a menu-driven program that accepts commands until the user chooses quit. Identify its selection structure, loop condition, validation rules, and termination mechanism.
  2. Trace a loop that processes marks from 0 to 100 and identify how it handles invalid input, the sentinel, and the no-data case.
  3. A program occasionally runs forever while waiting for input. Analyze at least three possible control-flow causes and propose a test for each.

Multiple Choice Questions with Answers

Question 1

Which operator tests equality in both Java and Python?

A. =

B. ==

C. !=

D. <=

Correct Answer: B. ==

Question 2

What is the main purpose of a guard condition?

A. To repeat a loop indefinitely

B. To reject invalid or exceptional cases early

C. To convert text into numbers

D. To compare object identities

Correct Answer: B. To reject invalid or exceptional cases early

Question 3

In Python, what values are produced by range(1, 4)?

A. 1, 2, 3

B. 1, 2, 3, 4

C. 0, 1, 2, 3

D. 2, 3, 4

Correct Answer: A. 1, 2, 3

Question 4

Which statement terminates the nearest enclosing loop?

A. pass

B. skip

C. continue

D. break

Correct Answer: D. break

Question 5

What is a likely result of omitting break in a traditional Java switch case?

A. The program always terminates

B. Execution may fall through to a later case

C. The switch becomes a while loop

D. The case is ignored at compile time

Correct Answer: B. Execution may fall through to a later case

Question 6

Which loop is most suitable for processing every item in a known collection?

A. for loop

B. while loop only

C. recursive loop only

D. conditional expression

Correct Answer: A. for loop

Question 7

Why should a program check count > 0 before calculating total / count?

A. To prevent division by zero

B. To sort the input

C. To force a loop to continue

D. To convert the result to a string

Correct Answer: A. To prevent division by zero

Question 8

What does continue do in a loop?

A. Exits all loops permanently

B. Repeats the previous iteration

C. Skips the rest of the current iteration

D. Pauses the program until input arrives

Correct Answer: C. Skips the rest of the current iteration

Question 9

Which Python construct is commonly used to emulate a do-while loop?

A. for item in list

B. while True with a controlled break

C. if followed by pass

D. match with a wildcard

Correct Answer: B. while True with a controlled break

Question 10

A nested loop has an outer loop executing 3 times and an inner loop executing 4 times for each outer iteration. How many times does the inner body execute?

A. 7

B. 9

C. 12

D. 16

Correct Answer: C. 12

Programming Fundamentals
Chapter 4 of 14