Unit 2.0: Control Structures 🔀
1. Introduction to Control Structures
- By default, a C++ program executes statements sequentially (top to bottom). Control structures change the flow of execution.
Types of Control Structures
Control Structures
│
├── Decision Making (Branching)
│ ├── if
│ ├── if-else
│ ├── nested if-else
│ ├── switch-case
│ └── ternary operator (? :)
│
├── Looping (Repetition/Iteration)
│ ├── for loop
│ ├── while loop
│ ├── do-while loop
│ └── nested loops
│
└── Jump Statements
├── break
├── continue
├── goto
└── return
Flow of Execution
#include <iostream>
using namespace std;
int main() {
// Sequential (default)
cout << "Step 1" << endl;
cout << "Step 2" << endl;
cout << "Step 3" << endl;
// With control structure
int x = 10;
if (x > 5) {
cout << "x is greater than 5" << endl; // This runs
}
if (x > 20) {
cout << "x is greater than 20" << endl; // This is SKIPPED
}
return 0;
}2. if Statement
The if statement executes a block of code only if a condition is true.
Syntax
if (condition) {
// code runs if condition is true
}Examples
#include <iostream>
using namespace std;
int main() {
int marks = 75;
// Basic if
if (marks >= 40) {
cout << "You passed!" << endl;
}
// Single-line if (no braces for single statement — not recommended)
if (marks >= 90)
cout << "Excellent!" << endl;
// Multiple conditions in one if
int age = 20;
bool hasID = true;
if (age >= 18 && hasID) {
cout << "Entry allowed." << endl;
}
// Checking range
double temperature = 38.5;
if (temperature > 37.5) {
cout << "Fever detected!" << endl;
cout << "Please consult a doctor." << endl;
}
return 0;
}Common Mistakes
int main() {
int x = 5;
// ❌ WRONG: = is assignment, not comparison
// if (x = 10) { ... } // Always true, x becomes 10
// ✅ CORRECT: == for comparison
if (x == 10) {
cout << "x is 10" << endl;
}
// ❌ WRONG: Semicolon after if (empty body)
// if (x > 0); // This does nothing regardless of condition
// {
// cout << "Always prints!" << endl; // Always executes
// }
return 0;
}3. if-else Statement
Provides an alternative path when the condition is false.
Syntax
if (condition) {
// runs if condition is TRUE
} else {
// runs if condition is FALSE
}Examples
#include <iostream>
using namespace std;
int main() {
// Example 1: Even or Odd
int num = 7;
if (num % 2 == 0) {
cout << num << " is Even" << endl;
} else {
cout << num << " is Odd" << endl;
}
// Output: 7 is Odd
// Example 2: Pass or Fail
int marks = 35;
if (marks >= 40) {
cout << "Result: PASS" << endl;
} else {
cout << "Result: FAIL" << endl;
}
// Example 3: Larger of two numbers
int a = 15, b = 23;
if (a > b) {
cout << "Larger: " << a << endl;
} else {
cout << "Larger: " << b << endl;
}
// Example 4: Login check
string password = "secret123";
string input = "secret123";
if (password == input) {
cout << "Login Successful!" << endl;
} else {
cout << "Incorrect Password!" << endl;
}
return 0;
}if-else if Ladder
#include <iostream>
using namespace std;
int main() {
int marks = 72;
char grade;
if (marks >= 90) {
grade = 'A';
} else if (marks >= 80) {
grade = 'B';
} else if (marks >= 70) {
grade = 'C';
} else if (marks >= 60) {
grade = 'D';
} else {
grade = 'F';
}
cout << "Marks: " << marks << " | Grade: " << grade << endl;
// Output: Marks: 72 | Grade: C
return 0;
}4. Nested if-else
An if or if-else inside another if or else block.
Syntax
if (condition1) {
if (condition2) {
// runs if BOTH condition1 AND condition2 are true
} else {
// runs if condition1 true BUT condition2 false
}
} else {
// runs if condition1 is false
}Examples
#include <iostream>
using namespace std;
int main() {
// Example 1: Number classification
int num = 15;
if (num >= 0) {
if (num == 0) {
cout << "Zero" << endl;
} else {
cout << "Positive number" << endl;
}
} else {
cout << "Negative number" << endl;
}
// Output: Positive number
// Example 2: Largest of three numbers
int a = 10, b = 30, c = 20;
if (a >= b) {
if (a >= c) {
cout << "Largest: " << a << endl;
} else {
cout << "Largest: " << c << endl;
}
} else {
if (b >= c) {
cout << "Largest: " << b << endl;
} else {
cout << "Largest: " << c << endl;
}
}
// Output: Largest: 30
return 0;
}Nested if-else: Voting Eligibility
#include <iostream>
using namespace std;
int main() {
int age = 20;
bool isCitizen = true;
bool isRegistered = true;
if (age >= 18) {
if (isCitizen) {
if (isRegistered) {
cout << "You can VOTE!" << endl;
} else {
cout << "Please register to vote first." << endl;
}
} else {
cout << "Only citizens can vote." << endl;
}
} else {
cout << "You must be 18+ to vote." << endl;
}
// Output: You can VOTE!
return 0;
}Tip: Avoid Deep Nesting
// ❌ Deep nesting (hard to read)
if (a > 0) {
if (b > 0) {
if (c > 0) {
cout << "All positive";
}
}
}
// ✅ Use logical AND instead
if (a > 0 && b > 0 && c > 0) {
cout << "All positive";
}5. goto Statement
goto jumps to a labeled statement in the same function. ⚠️ Avoid in modern C++ – makes code hard to read.
Syntax
goto label_name;
...
label_name:
// statementsExamples
#include <iostream>
using namespace std;
int main() {
int i = 1;
// Using goto like a loop (not recommended)
loop:
if (i <= 5) {
cout << i << " ";
i++;
goto loop;
}
cout << endl;
// Output: 1 2 3 4 5
return 0;
}goto for Error Handling (one valid use)
#include <iostream>
using namespace std;
int main() {
int x = -5;
if (x < 0) {
goto error; // Jump to error section
}
cout << "Processing: " << x << endl;
goto end;
error:
cout << "Error: Invalid input!" << endl;
end:
cout << "Program finished." << endl;
return 0;
}
// Output:
// Error: Invalid input!
// Program finished.⚠️ Note:
gotois generally considered bad practice because it creates “spaghetti code”. Usebreak,continue, or functions instead.
6. break Statement
break immediately exits the loop or switch-case it is in.
Syntax
for (...) {
if (condition) {
break; // exits the loop
}
}Examples
#include <iostream>
using namespace std;
int main() {
// Example 1: Exit loop early
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break; // Stop when i reaches 6
}
cout << i << " ";
}
cout << endl;
// Output: 1 2 3 4 5
// Example 2: Search in array
int arr[] = {10, 25, 30, 45, 50};
int target = 30;
bool found = false;
for (int i = 0; i < 5; i++) {
if (arr[i] == target) {
cout << "Found " << target << " at index " << i << endl;
found = true;
break; // No need to search further
}
}
if (!found) {
cout << target << " not found" << endl;
}
// Output: Found 30 at index 2
// Example 3: break in while loop
int n = 1;
while (true) { // infinite loop
cout << n << " ";
n++;
if (n > 5) break; // exit condition
}
cout << endl;
// Output: 1 2 3 4 5
return 0;
}break in Nested Loops
#include <iostream>
using namespace std;
int main() {
// break only exits the INNERMOST loop
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) break; // exits inner loop only
cout << "(" << i << "," << j << ") ";
}
}
cout << endl;
// Output: (1,1) (2,1) (3,1)
return 0;
}7. continue Statement
continue skips the current iteration and moves to the next one.
Syntax
for (...) {
if (condition) {
continue; // skip rest of this iteration
}
// this code is skipped when continue is hit
}Examples
#include <iostream>
using namespace std;
int main() {
// Example 1: Print only odd numbers
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
cout << i << " ";
}
cout << endl;
// Output: 1 3 5 7 9
// Example 2: Skip a specific value
for (int i = 1; i <= 7; i++) {
if (i == 4) {
continue;
}
cout << i << " ";
}
cout << endl;
// Output: 1 2 3 5 6 7
// Example 3: Skip negative numbers in sum
int nums[] = {3, -1, 5, -2, 8, -4, 2};
int sum = 0;
for (int i = 0; i < 7; i++) {
if (nums[i] < 0) {
continue; // skip negatives
}
sum += nums[i];
}
cout << "Sum of positives: " << sum << endl;
// Output: Sum of positives: 18
return 0;
}break vs continue
#include <iostream>
using namespace std;
int main() {
cout << "break example: ";
for (int i = 1; i <= 5; i++) {
if (i == 3) break; // STOPS the loop
cout << i << " ";
}
cout << endl;
// Output: 1 2
cout << "continue example: ";
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // SKIPS iteration 3
cout << i << " ";
}
cout << endl;
// Output: 1 2 4 5
return 0;
}8. switch-case Statement
switch compares a variable against multiple values and executes the matching case.
Syntax
switch (expression) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
...
default:
// code if no case matches
}Examples
#include <iostream>
using namespace std;
int main() {
// Example 1: Day of week
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day" << endl;
}
// Output: Wednesday
return 0;
}Simple Calculator using switch
#include <iostream>
using namespace std;
int main() {
double a, b;
char op;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "Enter operator (+, -, *, /): ";
cin >> op;
switch (op) {
case '+':
cout << "Result: " << a + b << endl;
break;
case '-':
cout << "Result: " << a - b << endl;
break;
case '*':
cout << "Result: " << a * b << endl;
break;
case '/':
if (b != 0)
cout << "Result: " << a / b << endl;
else
cout << "Error: Division by zero!" << endl;
break;
default:
cout << "Unknown operator!" << endl;
}
return 0;
}Fall-through (Without break)
#include <iostream>
using namespace std;
int main() {
int month = 4;
// Groups of months with same days
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
cout << "31 days" << endl;
break;
case 4:
case 6:
case 9:
case 11:
cout << "30 days" << endl; // April → Output: 30 days
break;
case 2:
cout << "28 or 29 days" << endl;
break;
default:
cout << "Invalid month" << endl;
}
return 0;
}switch vs if-else
| Feature | switch | if-else |
|---|---|---|
| Condition type | Equality only (int, char, enum) | Any boolean expression |
| Speed | Faster (jump table) | Slightly slower |
| Range check | ❌ Not directly | ✅ Yes (x > 5 && x < 10) |
| Float/String | ❌ Not supported | ✅ Supported |
| Readability | ✅ Better for many cases | ✅ Better for ranges |
9. for Loop
The for loop repeats a block of code a known number of times.
Syntax
for (initialization; condition; update) {
// code to repeat
}Flow
initialization → check condition → (if true) execute body → update → check condition → ...
Examples
#include <iostream>
using namespace std;
int main() {
// Example 1: Print 1 to 10
for (int i = 1; i <= 10; i++) {
cout << i << " ";
}
cout << endl;
// Output: 1 2 3 4 5 6 7 8 9 10
// Example 2: Sum of first N natural numbers
int n = 100, sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
cout << "Sum = " << sum << endl; // 5050
// Example 3: Counting down
for (int i = 10; i >= 1; i--) {
cout << i << " ";
}
cout << "GO!" << endl;
// Example 4: Step by 2
for (int i = 0; i <= 20; i += 2) {
cout << i << " ";
}
cout << endl;
// Output: 0 2 4 6 8 10 12 14 16 18 20
// Example 5: Multiplication table
int num = 7;
for (int i = 1; i <= 10; i++) {
cout << num << " x " << i << " = " << num * i << endl;
}
return 0;
}for Loop with Arrays
#include <iostream>
using namespace std;
int main() {
int marks[] = {85, 72, 91, 68, 78};
int n = 5;
int total = 0;
for (int i = 0; i < n; i++) {
total += marks[i];
cout << "Student " << i+1 << ": " << marks[i] << endl;
}
double average = (double)total / n;
cout << "Average: " << average << endl;
return 0;
}Range-based for Loop (C++11)
#include <iostream>
#include <vector>
using namespace std;
int main() {
// With array
int nums[] = {10, 20, 30, 40, 50};
for (int x : nums) {
cout << x << " ";
}
cout << endl;
// With vector
vector<string> fruits = {"Apple", "Banana", "Cherry"};
for (string fruit : fruits) {
cout << fruit << endl;
}
// With reference (can modify)
for (int& x : nums) {
x *= 2;
}
for (int x : nums) {
cout << x << " ";
}
// Output: 20 40 60 80 100
return 0;
}Infinite for Loop
// Infinite loop (used when exit condition is complex)
for (;;) {
cout << "This runs forever" << endl;
// Must use break to exit
break;
}10. Nested for Loop
A for loop inside another for loop. Inner loop completes all its iterations for each iteration of the outer loop.
Syntax
for (outer init; outer condition; outer update) {
for (inner init; inner condition; inner update) {
// executes n_outer × n_inner times
}
}Multiplication Table
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
cout << i * j << "\t";
}
cout << endl;
}
return 0;
}
/*
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
*/Star Patterns
#include <iostream>
using namespace std;
int main() {
int n = 5;
// Pattern 1: Right-angle triangle
cout << "Right Triangle:" << endl;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
/*
*
* *
* * *
* * * *
* * * * *
*/
cout << endl;
// Pattern 2: Inverted triangle
cout << "Inverted Triangle:" << endl;
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
cout << endl;
// Pattern 3: Full pyramid
cout << "Pyramid:" << endl;
for (int i = 1; i <= n; i++) {
for (int j = i; j < n; j++) {
cout << " "; // spaces
}
for (int j = 1; j <= (2*i - 1); j++) {
cout << "* ";
}
cout << endl;
}
/*
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
*/
return 0;
}2D Array Processing
#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Print matrix
cout << "Matrix:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
// Sum of all elements
int sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sum += matrix[i][j];
}
}
cout << "Sum: " << sum << endl; // 45
return 0;
}11. while Loop
The while loop repeats as long as a condition is true. Use when the number of iterations is not known in advance.
Syntax
while (condition) {
// code to repeat
// must eventually make condition false!
}Examples
#include <iostream>
using namespace std;
int main() {
// Example 1: Countdown
int count = 5;
while (count > 0) {
cout << count << " ";
count--;
}
cout << "Blast off!" << endl;
// Output: 5 4 3 2 1 Blast off!
// Example 2: Sum of digits
int number = 12345;
int digitSum = 0;
while (number > 0) {
digitSum += number % 10; // get last digit
number /= 10; // remove last digit
}
cout << "Digit sum: " << digitSum << endl; // 15
// Example 3: Reverse a number
int n = 1234;
int reversed = 0;
while (n > 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
cout << "Reversed: " << reversed << endl; // 4321
return 0;
}Input Validation with while
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter age (1-120): ";
cin >> age;
while (age < 1 || age > 120) {
cout << "Invalid! Enter age between 1 and 120: ";
cin >> age;
}
cout << "Valid age: " << age << endl;
return 0;
}Finding Factorial
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
long long factorial = 1;
int i = 1;
while (i <= n) {
factorial *= i;
i++;
}
cout << n << "! = " << factorial << endl;
// For n=5: 5! = 120
return 0;
}12. do-while Loop
The do-while loop executes the body at least once, then checks the condition.
Syntax
do {
// code runs at least once
} while (condition); // Note the semicolon!Key Difference from while
#include <iostream>
using namespace std;
int main() {
int x = 10;
// while: checks condition FIRST
while (x < 5) {
cout << "while: " << x << endl; // Never executes
}
// do-while: executes FIRST, then checks
do {
cout << "do-while: " << x << endl; // Executes once!
} while (x < 5);
// Output: do-while: 10
return 0;
}Examples
#include <iostream>
using namespace std;
int main() {
// Example 1: Print 1 to 5
int i = 1;
do {
cout << i << " ";
i++;
} while (i <= 5);
cout << endl;
// Output: 1 2 3 4 5
// Example 2: Menu-driven program
int choice;
do {
cout << "\n=== MENU ===" << endl;
cout << "1. Say Hello" << endl;
cout << "2. Show Date" << endl;
cout << "3. Exit" << endl;
cout << "Enter choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Hello, World!" << endl;
break;
case 2:
cout << "Today is a great day!" << endl;
break;
case 3:
cout << "Goodbye!" << endl;
break;
default:
cout << "Invalid choice!" << endl;
}
} while (choice != 3); // Keep showing menu until user exits
return 0;
}ATM PIN Verification
#include <iostream>
using namespace std;
int main() {
const int CORRECT_PIN = 1234;
int enteredPin;
int attempts = 0;
const int MAX_ATTEMPTS = 3;
do {
cout << "Enter your PIN: ";
cin >> enteredPin;
attempts++;
if (enteredPin == CORRECT_PIN) {
cout << "Access Granted! Welcome." << endl;
break;
} else {
cout << "Incorrect PIN. Attempts remaining: "
<< (MAX_ATTEMPTS - attempts) << endl;
}
} while (attempts < MAX_ATTEMPTS);
if (attempts == MAX_ATTEMPTS && enteredPin != CORRECT_PIN) {
cout << "Account locked! Too many failed attempts." << endl;
}
return 0;
}13. Loop Comparison & Best Practices
When to Use Which Loop
| Loop | Best Used When |
|---|---|
for | Number of iterations is known |
while | Iterations depend on a condition (unknown count) |
do-while | Body must execute at least once (menu, input validation) |
Comparison Example
#include <iostream>
using namespace std;
int main() {
// All three print 1 to 5
// for loop
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
cout << endl;
// while loop
int i = 1;
while (i <= 5) {
cout << i << " ";
i++;
}
cout << endl;
// do-while loop
i = 1;
do {
cout << i << " ";
i++;
} while (i <= 5);
cout << endl;
return 0;
}Avoiding Common Mistakes
// ❌ Infinite loop (forgot to update i)
for (int i = 0; i < 10; ) {
cout << i;
// i never changes → infinite loop!
}
// ❌ Off-by-one error
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i <= 5; i++) { // i <= 5 goes out of bounds!
cout << arr[i];
}
// ✅ Correct
for (int i = 0; i < 5; i++) {
cout << arr[i];
}
// ❌ Condition never becomes false
int x = 10;
while (x > 0) {
cout << x;
x++; // x increases, never reaches 0!
}
// ✅ Correct
while (x > 0) {
cout << x;
x--; // decrements toward 0
}14. Practical Programs
Program 1: Prime Number Check
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
bool isPrime = true;
if (n < 2) {
isPrime = false;
} else {
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
cout << n << " is PRIME" << endl;
else
cout << n << " is NOT prime" << endl;
return 0;
}Program 2: Fibonacci Series
#include <iostream>
using namespace std;
int main() {
int n;
cout << "How many Fibonacci terms? ";
cin >> n;
int a = 0, b = 1;
cout << "Fibonacci: ";
for (int i = 1; i <= n; i++) {
cout << a;
if (i < n) cout << ", ";
int temp = a + b;
a = b;
b = temp;
}
cout << endl;
// For n=8: 0, 1, 1, 2, 3, 5, 8, 13
return 0;
}Program 3: Simple Number Guessing Game
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(0));
int secret = rand() % 100 + 1; // random 1-100
int guess;
int attempts = 0;
cout << "Guess the number (1-100)!" << endl;
do {
cout << "Your guess: ";
cin >> guess;
attempts++;
if (guess < secret)
cout << "Too LOW! Try higher." << endl;
else if (guess > secret)
cout << "Too HIGH! Try lower." << endl;
else
cout << "Correct! You got it in " << attempts << " attempts!" << endl;
} while (guess != secret);
return 0;
}Program 4: Student Grade Calculator
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter number of students: ";
cin >> n;
for (int i = 1; i <= n; i++) {
string name;
int marks;
cout << "\nStudent " << i << " name: ";
cin >> name;
cout << "Marks (0-100): ";
cin >> marks;
// Validate input
while (marks < 0 || marks > 100) {
cout << "Invalid! Enter marks (0-100): ";
cin >> marks;
}
// Assign grade
char grade;
string result;
if (marks >= 90) {
grade = 'A';
result = "Distinction";
} else if (marks >= 75) {
grade = 'B';
result = "First Class";
} else if (marks >= 60) {
grade = 'C';
result = "Second Class";
} else if (marks >= 40) {
grade = 'D';
result = "Pass";
} else {
grade = 'F';
result = "Fail";
}
cout << name << " | Marks: " << marks
<< " | Grade: " << grade
<< " | Result: " << result << endl;
}
return 0;
}Program 5: Number Pattern
#include <iostream>
using namespace std;
int main() {
int n = 5;
// Floyd's Triangle
cout << "Floyd's Triangle:" << endl;
int num = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
cout << num++ << "\t";
}
cout << endl;
}
/*
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
*/
return 0;
}Quick Reference Cheat Sheet
Decision Statements
// if
if (x > 0) { ... }
// if-else
if (x > 0) { ... } else { ... }
// if-else if-else
if (x > 0) { ... }
else if (x < 0) { ... }
else { ... }
// nested if
if (x > 0) {
if (x > 100) { ... }
}
// switch
switch (x) {
case 1: ...; break;
case 2: ...; break;
default: ...;
}Loop Statements
// for
for (int i = 0; i < n; i++) { ... }
// while
while (condition) { ... }
// do-while
do { ... } while (condition);
// range-based for (C++11)
for (auto x : container) { ... }Jump Statements
break; // exit loop/switch
continue; // skip to next iteration
goto label; // jump to label (avoid!)
return; // exit function