C++ Programming
Control Flow
Master C++ programming from basics to advanced. Learn object-oriented programming, STL, memory management, and build high-performance applications.
On this page
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:
1if (condition) {
2 // code to execute if condition is true
3}
Example:
1int age = 20;
2if (age >= 18) {
3 cout << "You are an adult" << endl;
4}
Sample Output
You are an adult
2. If-Else Statement
Execute one block if condition is true, another if false.
Syntax:
1if (condition) {
2 // code if true
3} else {
4 // code if false
5}
Example:
1int score = 85;
2if (score >= 60) {
3 cout << "Passed" << endl;
4} else {
5 cout << "Failed" << endl;
6}
Sample Output
Passed Failed
3. If-Else If-Else Statement
Handle multiple conditions.
Syntax:
1if (condition1) {
2 // code for condition1
3} else if (condition2) {
4 // code for condition2
5} else if (condition3) {
6 // code for condition3
7} else {
8 // code if none are true
9}
Example:
1int score = 85;
2if (score >= 90) {
3 cout << "Grade: A" << endl;
4} else if (score >= 80) {
5 cout << "Grade: B" << endl;
6} else if (score >= 70) {
7 cout << "Grade: C" << endl;
8} else if (score >= 60) {
9 cout << "Grade: D" << endl;
10} else {
11 cout << "Grade: F" << endl;
12}
Sample Output
Grade: A Grade: B Grade: C Grade: D Grade: F
4. Nested If Statements
If statements inside other if statements.
Example:
1int age = 20;
2bool hasLicense = true;
3
4if (age >= 18) {
5 if (hasLicense) {
6 cout << "You can drive" << endl;
7 } else {
8 cout << "You need a license" << endl;
9 }
10} else {
11 cout << "You are too young" << endl;
12}
Sample Output
You can drive You need a license You are too young
5. Switch Statement
Efficient way to handle multiple conditions based on a single variable.
Syntax:
1switch (variable) {
2 case value1:
3 // code
4 break;
5 case value2:
6 // code
7 break;
8 default:
9 // code if no case matches
10}
Example:
1int day = 3;
2switch (day) {
3 case 1:
4 cout << "Monday" << endl;
5 break;
6 case 2:
7 cout << "Tuesday" << endl;
8 break;
9 case 3:
10 cout << "Wednesday" << endl;
11 break;
12 default:
13 cout << "Other day" << endl;
14}
Sample Output
Monday Tuesday Wednesday Other day
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:
1for (initialization; condition; increment) {
2 // code to repeat
3}
Example:
1for (int i = 0; i < 5; i++) {
2 cout << i << " ";
3}
4// Output: 0 1 2 3 4
Parts:
- Initialization: Executes once at start
- Condition: Checked before each iteration
- Increment: Executes after each iteration
Common Patterns:
1// Count from 0 to 9
2for (int i = 0; i < 10; i++) { }
3
4// Count from 1 to 10
5for (int i = 1; i <= 10; i++) { }
6
7// Count backwards
8for (int i = 10; i > 0; i--) { }
9
10// Count by 2s
11for (int i = 0; i < 10; i += 2) { }
2. While Loop
Repeat code while condition is true.
Syntax:
1while (condition) {
2 // code to repeat
3}
Example:
1int count = 0;
2while (count < 5) {
3 cout << count << " ";
4 count++;
5}
6// 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:
1do {
2 // code to repeat
3} while (condition);
Example:
1int number;
2do {
3 cout << "Enter positive number: ";
4 cin >> number;
5} while (number <= 0);
Sample Output
Enter positive number:
Difference from while: Do-while always executes at least once, even if condition is false initially.
4. Nested Loops
Loops inside other loops.
Example:
1for (int i = 1; i <= 3; i++) {
2 for (int j = 1; j <= 3; j++) {
3 cout << i << "," << j << " ";
4 }
5 cout << endl;
6}
7// Output:
8// 1,1 1,2 1,3
9// 2,1 2,2 2,3
10// 3,1 3,2 3,3
Sample Output
,
Loop Control Statements
Break Statement
Exit the loop immediately.
Example:
1for (int i = 0; i < 10; i++) {
2 if (i == 5) {
3 break; // Exit loop when i is 5
4 }
5 cout << i << " ";
6}
7// Output: 0 1 2 3 4
Continue Statement
Skip to next iteration of the loop.
Example:
1for (int i = 0; i < 10; i++) {
2 if (i % 2 == 0) {
3 continue; // Skip even numbers
4 }
5 cout << i << " ";
6}
7// Output: 1 3 5 7 9
Range-Based For Loop (C++11)
Iterate over elements in a container (arrays, vectors, etc.).
Syntax:
1for (type element : container) {
2 // code
3}
Example:
1int arr[] = {1, 2, 3, 4, 5};
2for (int num : arr) {
3 cout << num << " ";
4}
5// Output: 1 2 3 4 5
Common Patterns
Pattern 1: Sum of Numbers
1int sum = 0;
2for (int i = 1; i <= 100; i++) {
3 sum += i;
4}
5cout << "Sum: " << sum << endl;
Sample Output
Sum:
Pattern 2: Finding Maximum
1int max = arr[0];
2for (int i = 1; i < size; i++) {
3 if (arr[i] > max) {
4 max = arr[i];
5 }
6}
Pattern 3: Input Validation
1int number;
2do {
3 cout << "Enter number (1-10): ";
4 cin >> number;
5} while (number < 1 || number > 10);
Sample Output
Enter number (1-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.
Sample Output
You passed! Grade: B You can drive
Practice with Programs
Reinforce your learning with hands-on practice programs
Related Program Topics
Recommended Programs
Check for Even Odd
BeginnerCheck whether an integer is even or odd in C++ using the % operator and an if/else. Covers zero, negative numbers, and why == 1 is the wrong test for odd.
Largest Among 3
BeginnerFind the largest of three numbers in C++ with an if / else if / else chain and the && operator. Shows why >= matters when two inputs tie for the maximum.
Vowel/Consonant Check
BeginnerCheck whether a character is a vowel, a consonant, or not a letter in C++. Uses tolower from <cctype>, the || operator, and a range test on 'a' to 'z'.
Multiplication Table
BeginnerPrint the multiplication table of any number from 1 to 10 in C++ using a for loop. Shows how the loop counter changes and why <= 10 differs from < 10.
Sum of n Natural Numbers
BeginnerAdd the numbers 1 to n in C++ with a for loop and a running total. Compare the loop with the n(n+1)/2 formula and see what happens for n = 0 or a huge n.