LanguagesCore FundamentalsControl Flow

Control Flow

Core Fundamentals

What is Control Flow?

Control flow (or flow of control) is the order in which a computer executes statements in a program. By default, code is executed sequentially from top to bottom. However, programming languages provide control flow statements that allow you to alter this sequence, enabling your program to make decisions, repeat actions, and jump to different sections of code.

Mastering control flow is fundamental to programming, as it's how you implement logic and algorithms.

1. Conditional Statements

Conditional statements allow a program to execute different blocks of code based on whether a certain condition is true or false.

if Statement

The most basic conditional. The code block inside the if statement is executed only if the condition is true.

age = 20
if age >= 18:
    print("You are an adult.")

if-else Statement

Provides an alternative block of code to execute if the if condition is false.

age = 16
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

if-elif-else (or if-else if-else) Statement

Allows you to check multiple conditions in sequence. As soon as a true condition is found, its block is executed, and the rest of the chain is skipped.

score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B") # This will be printed
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

switch Statement

A switch (or match in some newer languages like Python 3.10+) statement is an alternative to a long if-elif-else chain. It compares a single variable against a series of constant values (case). It can be cleaner and sometimes more efficient.

Interview Hot Point: The break keyword

In languages like Java, C++, and JavaScript, each case block must end with a break statement. If you forget it, the program will "fall through" and execute the code in the next case as well, which is a common source of bugs.

// Java
int day = 3;
String dayName;
switch (day) {
    case 1: dayName = "Monday"; break;
    case 2: dayName = "Tuesday"; break;
    case 3: dayName = "Wednesday"; break; // Prints "Wednesday"
    case 4: dayName = "Thursday"; break;
    case 5: dayName = "Friday"; break;
    default: dayName = "Weekend"; break;
}
System.out.println(dayName);

2. Looping Constructs

Loops are used to execute a block of code repeatedly as long as a condition is met.

for Loop

Used for iterating over a sequence (like a list, array, or string) or for a specific number of times.

# Python: Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Looping a specific number of times
for i in range(5): # 0 to 4
    print(i)

while Loop

Executes a block of code as long as a specified condition is true. The condition is checked before each iteration.

count = 0
while count < 5:
    print(count)
    count += 1 # Important: Must increment to avoid an infinite loop

do-while Loop

Similar to a while loop, but the condition is checked after the iteration. This guarantees that the code block is executed at least once. Python does not have a do-while loop.

// Java
int count = 5;
do {
    // This will print 5, and then the loop will terminate.
    System.out.println(count);
    count++;
} while (count < 5);

3. Loop Control Statements

These statements change the normal execution of a loop.

break

Immediately terminates the innermost loop it's in.

for i in range(10):
    if i == 5:
        break # Stops the loop when i is 5
    print(i) # Prints 0, 1, 2, 3, 4

continue

Skips the rest of the current iteration and proceeds to the next one.

for i in range(10):
    if i % 2 == 0: # If i is even
        continue   # Skip the print statement for this iteration
    print(i) # Prints 1, 3, 5, 7, 9

return

The return statement is used within a function to exit the function and, optionally, pass a value back to the caller. If a return is executed inside a loop that is inside a function, it will terminate not only the loop but the entire function.