Module 4: Control Flow
Chapter 4 • Beginner
Control Flow
Control flow statements allow your program to make decisions and repeat code. They are essential for creating dynamic, interactive programs.
What is Control Flow?
Control flow determines the order in which statements are executed in your program. It includes:
- Conditional statements: Execute code based on conditions (if/else, switch)
- Loops: Repeat code multiple times (for, while, do-while)
Conditional Statements
1. If Statement
Execute code only if a condition is true.
Syntax:
if (condition) {
// code to execute if condition is true
}
Example:
int age = 20;
if (age >= 18) {
cout << "You are an adult" << endl;
}
2. If-Else Statement
Execute one block if condition is true, another if false.
Syntax:
if (condition) {
// code if true
} else {
// code if false
}
Example:
int score = 85;
if (score >= 60) {
cout << "Passed" << endl;
} else {
cout << "Failed" << endl;
}
3. If-Else If-Else Statement
Handle multiple conditions.
Syntax:
if (condition1) {
// code for condition1
} else if (condition2) {
// code for condition2
} else if (condition3) {
// code for condition3
} else {
// code if none are true
}
Example:
int score = 85;
if (score >= 90) {
cout << "Grade: A" << endl;
} else if (score >= 80) {
cout << "Grade: B" << endl;
} else if (score >= 70) {
cout << "Grade: C" << endl;
} else if (score >= 60) {
cout << "Grade: D" << endl;
} else {
cout << "Grade: F" << endl;
}
4. Nested If Statements
If statements inside other if statements.
Example:
int age = 20;
bool hasLicense = true;
if (age >= 18) {
if (hasLicense) {
cout << "You can drive" << endl;
} else {
cout << "You need a license" << endl;
}
} else {
cout << "You are too young" << endl;
}
5. Switch Statement
Efficient way to handle multiple conditions based on a single variable.
Syntax:
switch (variable) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code if no case matches
}
Example:
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
default:
cout << "Other day" << endl;
}
Important Notes:
- Use
breakto exit switch (otherwise execution continues to next case) defaulthandles unmatched values- Switch only works with integers, characters, and enums (not strings in older C++)
Loops
Loops allow you to repeat code multiple times.
1. For Loop
Execute code a specific number of times.
Syntax:
for (initialization; condition; increment) {
// code to repeat
}
Example:
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
// Output: 0 1 2 3 4
Parts:
- Initialization: Executes once at start
- Condition: Checked before each iteration
- Increment: Executes after each iteration
Common Patterns:
// Count from 0 to 9
for (int i = 0; i < 10; i++) { }
// Count from 1 to 10
for (int i = 1; i <= 10; i++) { }
// Count backwards
for (int i = 10; i > 0; i--) { }
// Count by 2s
for (int i = 0; i < 10; i += 2) { }
2. While Loop
Repeat code while condition is true.
Syntax:
while (condition) {
// code to repeat
}
Example:
int count = 0;
while (count < 5) {
cout << count << " ";
count++;
}
// Output: 0 1 2 3 4
Important: Make sure condition eventually becomes false, or you'll have an infinite loop!
3. Do-While Loop
Execute code at least once, then repeat while condition is true.
Syntax:
do {
// code to repeat
} while (condition);
Example:
int number;
do {
cout << "Enter positive number: ";
cin >> number;
} while (number <= 0);
Difference from while: Do-while always executes at least once, even if condition is false initially.
4. Nested Loops
Loops inside other loops.
Example:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
cout << i << "," << j << " ";
}
cout << endl;
}
// Output:
// 1,1 1,2 1,3
// 2,1 2,2 2,3
// 3,1 3,2 3,3
Loop Control Statements
Break Statement
Exit the loop immediately.
Example:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit loop when i is 5
}
cout << i << " ";
}
// Output: 0 1 2 3 4
Continue Statement
Skip to next iteration of the loop.
Example:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
cout << i << " ";
}
// Output: 1 3 5 7 9
Range-Based For Loop (C++11)
Iterate over elements in a container (arrays, vectors, etc.).
Syntax:
for (type element : container) {
// code
}
Example:
int arr[] = {1, 2, 3, 4, 5};
for (int num : arr) {
cout << num << " ";
}
// Output: 1 2 3 4 5
Common Patterns
Pattern 1: Sum of Numbers
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
cout << "Sum: " << sum << endl;
Pattern 2: Finding Maximum
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
Pattern 3: Input Validation
int number;
do {
cout << "Enter number (1-10): ";
cin >> number;
} while (number < 1 || number > 10);
Best Practices
- ✅ Use meaningful variable names in loops (
i,jare okay for simple loops) - ✅ Initialize loop variables properly
- ✅ Ensure loop termination (avoid infinite loops)
- ✅ Use appropriate loop type:
forwhen you know number of iterationswhilewhen condition is checked firstdo-whilewhen you need at least one execution
- ✅ Keep loop bodies simple - extract complex logic to functions
- ✅ Use `break` and `continue` sparingly - they can make code harder to read
Common Mistakes
- ❌ Infinite loops (condition never becomes false)
- ❌ Off-by-one errors (
i <= 10vsi < 10) - ❌ Forgetting
breakin switch statements - ❌ Modifying loop variable inside loop body incorrectly
- ❌ Using
=instead of==in conditions
Next Module
In Module 5, we'll learn about Functions - how to organize code into reusable blocks and make your programs more modular!
Hands-on Examples
If-Else Statements
#include <iostream>
using namespace std;
int main() {
int score = 85;
// Simple if
if (score >= 60) {
cout << "You passed!" << endl;
}
// If-else
if (score >= 90) {
cout << "Grade: A" << endl;
} else if (score >= 80) {
cout << "Grade: B" << endl;
} else if (score >= 70) {
cout << "Grade: C" << endl;
} else if (score >= 60) {
cout << "Grade: D" << endl;
} else {
cout << "Grade: F" << endl;
}
// Nested if
int age = 20;
bool hasLicense = true;
if (age >= 18) {
if (hasLicense) {
cout << "You can drive" << endl;
} else {
cout << "Get a license first" << endl;
}
} else {
cout << "Too young to drive" << endl;
}
return 0;
}If-else statements allow your program to make decisions. The first condition that is true executes its block. If none are true, the else block executes. You can nest if statements for complex logic.
Practice with Programs
Reinforce your learning with hands-on practice programs
Related Program Topics
Recommended Programs
Check for Even Odd
BeginnerProgram to check if a number is even or odd
Largest Among 3
BeginnerProgram to find the largest of three numbers
Vowel/Consonant Check
BeginnerProgram to check if a character is a vowel or consonant
Multiplication Table
BeginnerProgram to print multiplication table of a number
Sum of n Natural Numbers
BeginnerProgram to calculate sum of first n natural numbers