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.")
int age = 20;
if (age >= 18) {
System.out.println("You are an adult.");
}
let age = 20;
if (age >= 18) {
console.log("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.")
int age = 16;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
let age = 16;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("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")
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B"); // This will be printed
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B"); // This will be printed
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("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);
// JavaScript
let day = 3;
let dayName;
switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break; // Prints "Wednesday"
// If 'break' was missing here, it would fall through and assign "Thursday"
case 4: dayName = "Thursday"; break;
default: dayName = "Weekend"; break;
}
console.log(dayName);
# Python 3.10+ using match-case
day = 3
day_name = ""
match day:
case 1: day_name = "Monday"
case 2: day_name = "Tuesday"
case 3: day_name = "Wednesday" # Prints "Wednesday"
case 4: day_name = "Thursday"
case _: day_name = "Weekend" # Default case
print(day_name)
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)
// Java: Traditional for loop
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// Enhanced for-each loop
String[] fruits = {"apple", "banana", "cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
// JavaScript: Traditional for loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// For...of loop (for iterable objects like arrays)
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
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
int count = 0;
while (count < 5) {
System.out.println(count);
count++; // Important!
}
let count = 0;
while (count < 5) {
console.log(count);
count++; // Important!
}
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);
// JavaScript
let count = 5;
do {
// This will log 5, and then the loop will terminate.
console.log(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.