Control Flow in C++
1. What is Control Flow?
Control flow refers to the order in which statements and instructions are executed in a C++ program.
Normally, a program executes statements from top to bottom. Control flow statements allow us to change this order based on conditions, repetition, or program logic.
For example:
Start ↓ Statement 1 ↓ Condition ↓ Statement 2 ↓ End
C++ provides several control flow statements for decision-making, loops, and jumping between parts of a program.
2. Types of Control Flow
The major types of control flow in C++ are:
Control Flow │ ├── Sequential Control Flow │ ├── Selection / Decision Making │ ├── if │ ├── if-else │ ├── else-if │ └── switch │ ├── Iteration / Looping │ ├── for │ ├── while │ └── do-while │ └── Jump Statements ├── break ├── continue ├── return └── goto
3. Sequential Control Flow
In sequential execution, statements are executed one after another in the order in which they appear.
Example:
#include <iostream> using namespace std; int main() { cout << "First statement" << endl; cout << "Second statement" << endl; cout << "Third statement" << endl; return 0; }
Output:
First statement Second statement Third statement
The statements execute from top to bottom.
4. Decision-Making Statements
Decision-making statements allow a program to execute different code depending on whether a condition is true or false.
4.1 if Statement
The if statement executes a block of code only when its condition is true.
Syntax
if (condition) { // statements }
Example
#include <iostream> using namespace std; int main() { int age = 20; if (age >= 18) { cout << "You are an adult."; } return 0; }
Output:
You are an adult.
5. if-else Statement
The if-else statement provides two possible paths.
- If the condition is true →
ifblock executes. - If the condition is false →
elseblock executes.
Syntax
if (condition) { // true block } else { // false block }
Example
#include <iostream> using namespace std; int main() { int age; cout << "Enter your age: "; cin >> age; if (age >= 18) { cout << "Eligible."; } else { cout << "Not eligible."; } return 0; }
6. if-else-if Statement
The else-if structure is used when there are multiple conditions.
Syntax
if (condition1) { // code } else if (condition2) { // code } else { // code }
Example
#include <iostream> using namespace std; int main() { int marks; cout << "Enter marks: "; cin >> marks; if (marks >= 80) { cout << "Grade A"; } else if (marks >= 60) { cout << "Grade B"; } else if (marks >= 40) { cout << "Grade C"; } else { cout << "Fail"; } return 0; }
Example:
Enter marks: 75 Grade B
7. Nested if
An if statement inside another if statement is called a nested if.
Example:
#include <iostream> using namespace std; int main() { int age = 20; bool citizen = true; if (age >= 18) { if (citizen) { cout << "Condition satisfied."; } } return 0; }
Nested if statements are useful when one condition depends on another.
8. switch Statement
The switch statement is useful when one expression needs to be compared with several constant case values.
Syntax
switch (expression) { case value1: // statements break; case value2: // statements break; default: // statements }
Example
#include <iostream> using namespace std; int main() { int day; cout << "Enter day number (1-3): "; cin >> day; switch (day) { case 1: cout << "Sunday"; break; case 2: cout << "Monday"; break; case 3: cout << "Tuesday"; break; default: cout << "Invalid day"; } return 0; }
Example output:
Enter day number (1-3): 2 Monday
Importance of break
break normally stops execution from continuing into the next case.
Without break, execution can continue into subsequent cases, a behavior called fallthrough.
9. default in Switch
The default block executes when none of the cases match.
Example:
switch (choice) { case 1: cout << "Add"; break; case 2: cout << "Delete"; break; default: cout << "Invalid choice"; }
10. Loops
A loop repeatedly executes a block of code while a condition or iteration rule allows it.
C++ provides three main loops:
forwhiledo-while
11. for Loop
The for loop is commonly used when the number of iterations is known or controlled by a counter.
Syntax
for (initialization; condition; update) { // statements }
Example
#include <iostream> using namespace std; int main() { for (int i = 1; i <= 5; i++) { cout << i << endl; } return 0; }
Output:
1 2 3 4 5
How It Works
Initialization ↓ Condition ↓ Body ↓ Update ↓ Condition ↓ Repeat
12. while Loop
The while loop repeatedly executes a block as long as its condition is true.
Syntax
while (condition) { // statements }
Example
#include <iostream> using namespace std; int main() { int i = 1; while (i <= 5) { cout << i << endl; i++; } return 0; }
Output:
1 2 3 4 5
13. do-while Loop
The do-while loop executes its body at least once, because the condition is checked after the body.
Syntax
do { // statements } while (condition);
Example
#include <iostream> using namespace std; int main() { int i = 1; do { cout << i << endl; i++; } while (i <= 5); return 0; }
Output:
1 2 3 4 5
14. Difference Between while and do-while
| Feature | while | do-while |
|---|---|---|
| Condition checked | Before body | After body |
| Minimum executions | 0 | 1 |
| Syntax | while(condition) | do { } while(condition); |
| Suitable for | Condition-first repetition | Body must execute at least once |
Example:
int x = 10; while (x < 5) { cout << "Hello"; }
The body does not execute.
But:
int x = 10; do { cout << "Hello"; } while (x < 5);
The body executes once.
15. Nested Loops
A loop inside another loop is called a nested loop.
Example:
#include <iostream> using namespace std; int main() { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { cout << "* "; } cout << endl; } return 0; }
Output:
* * * * * * * * *
16. Range-Based for Loop
C++ provides a range-based for loop for iterating over elements of arrays and other range-based collections.
Example:
#include <iostream> using namespace std; int main() { int numbers[] = {10, 20, 30, 40, 50}; for (int number : numbers) { cout << number << endl; } return 0; }
Output:
10 20 30 40 50
17. break Statement
The break statement immediately terminates the nearest enclosing loop or switch.
Example:
#include <iostream> using namespace std; int main() { for (int i = 1; i <= 10; i++) { if (i == 5) { break; } cout << i << endl; } return 0; }
Output:
1 2 3 4
18. continue Statement
The continue statement skips the remaining statements in the current loop iteration and proceeds to the next iteration.
Example:
#include <iostream> using namespace std; int main() { for (int i = 1; i <= 5; i++) { if (i == 3) { continue; } cout << i << endl; } return 0; }
Output:
1 2 4 5
The value 3 is skipped.
19. return Statement
The return statement exits a function and can optionally provide a value to the caller.
Example:
#include <iostream> using namespace std; int add(int a, int b) { return a + b; } int main() { int result = add(10, 20); cout << result; return 0; }
Output:
30
In main(), return 0; commonly indicates successful program termination.
20. goto Statement
The goto statement transfers control directly to a labeled statement.
Syntax
goto label; label: // statements
Example:
#include <iostream> using namespace std; int main() { goto message; cout << "This will be skipped."; message: cout << "Hello C++!"; return 0; }
Output:
Hello C++!
Note
goto can make programs difficult to understand and maintain. Structured control flow such as loops, if, and functions is generally preferred.
21. Conditional Operator
The conditional operator ?: provides a compact way to select between two expressions.
Example:
#include <iostream> using namespace std; int main() { int age = 20; string result = (age >= 18) ? "Adult" : "Minor"; cout << result; return 0; }
Output:
Adult
22. Example: Checking Even or Odd
Control flow can be used to make decisions.
#include <iostream> using namespace std; int main() { int number; cout << "Enter a number: "; cin >> number; if (number % 2 == 0) { cout << "Even number"; } else { cout << "Odd number"; } return 0; }
Example:
Enter a number: 10 Even number
23. Example: Simple Menu
A switch statement can be used to create a simple menu.
#include <iostream> using namespace std; int main() { int choice; cout << "1. Add" << endl; cout << "2. Delete" << endl; cout << "3. Exit" << endl; cout << "Enter your choice: "; cin >> choice; switch (choice) { case 1: cout << "Add selected"; break; case 2: cout << "Delete selected"; break; case 3: cout << "Exit selected"; break; default: cout << "Invalid choice"; } return 0; }
24. Example: Sum of Numbers Using a Loop
#include <iostream> using namespace std; int main() { int n; int sum = 0; cout << "Enter a number: "; cin >> n; for (int i = 1; i <= n; i++) { sum += i; } cout << "Sum = " << sum; return 0; }
Input:
Enter a number: 5
Output:
Sum = 15
Calculation:
1 + 2 + 3 + 4 + 5 = 15
25. Control Flow Summary
| Category | Statements | Purpose |
|---|---|---|
| Sequential | Normal statements | Execute in order |
| Decision | if | Execute based on condition |
| Decision | if-else | Choose between two paths |
| Decision | else-if | Choose among multiple conditions |
| Decision | switch | Select among cases |
| Loop | for | Repeat using initialization, condition, and update |
| Loop | while | Repeat while condition is true |
| Loop | do-while | Execute at least once, then repeat |
| Jump | break | Exit loop or switch |
| Jump | continue | Skip current loop iteration |
| Jump | return | Exit a function |
| Jump | goto | Jump to a label |
| Conditional | ?: | Select between two expressions |
26. Important Points
- Control flow determines the execution order of a program.
ifis used for conditional execution.if-elseprovides two execution paths.else-ifhandles multiple conditions.switchis useful for selecting among case values.for,while, anddo-whileare used for repetition.breakterminates the nearest loop or switch.continueskips the current loop iteration.returnexits a function.gototransfers control to a labeled statement but should generally be avoided when structured alternatives are available.- The conditional operator
?:provides a short conditional expression.
Conclusion
Control flow is an important part of C++ programming because it allows a program to make decisions, repeat operations, and control the order in which instructions execute. Understanding if, switch, loops, and jump statements provides the foundation for writing logical and interactive C++ programs.