Control Structures in C++
- Published
- Updated
Control structures determine the order in which statements execute in a program. They allow a program to make decisions, repeat tasks, and respond to different conditions.
For example, a program can use control structures to check whether a student has passed an exam, display numbers from 1 to 10, or process every item in a shopping cart.
In this chapter, you will learn how to use conditional statements, loops, and jump statements in C++.
C++ programs use three basic control structures:
| Control structure | Purpose | Examples |
|---|---|---|
| Sequence | Executes statements in order | Assignments, calculations, output statements |
| Selection | Chooses which statements to execute | if, if...else, switch |
| Iteration | Repeats a block of statements | for, while, do...while |
C++ also provides statements such as break, continue, and return that change the normal flow of execution.
By default, C++ executes statements one after another in the order they appear.
Example
#include <iostream>
int main() {
int length = 8;
int width = 5;
int area = length * width;
std::cout << "Area: " << area << '\n';
return 0;
}
Output
Area: 40
The program first creates the variables, then calculates the area, and finally displays the result.
Conditional statements let a program choose an action based on whether a condition is true or false.
The if Statement
An if statement executes a block of code only when its condition is true.
Syntax
if (condition) {
// Executes when the condition is true.
}Example
int temperature = 35;
if (temperature > 30) {
std::cout << "It is a hot day.\n";
}Output
It is a hot day.If temperature were 25, the program would skip the block.
The if...else Statement
An if...else statement chooses between two blocks.
Syntax
if (condition) {
// Executes when the condition is true.
} else {
// Executes when the condition is false.
}Example
int number = 14;
if (number % 2 == 0) {
std::cout << "The number is even.\n";
} else {
std::cout << "The number is odd.\n";
}Output
The number is even.The remainder operator % returns the remainder after integer division. A number is even when dividing it by 2 leaves a remainder of 0.
The else if Ladder
Use an else if ladder when you need to check several conditions.
int marks = 76;
if (marks >= 90) {
std::cout << "Grade A\n";
} else if (marks >= 75) {
std::cout << "Grade B\n";
} else if (marks >= 60) {
std::cout << "Grade C\n";
} else if (marks >= 40) {
std::cout << "Grade D\n";
} else {
std::cout << "Grade F\n";
}Output
Grade BConditions are evaluated from top to bottom. Once a condition is true, its block executes and the remaining branches are skipped.
Order matters: If you checked marks >= 40 first, a score of 76 would match that condition before reaching the higher grade thresholds.
Nested if Statements
A nested if is an if statement inside another conditional block.
int age = 22;
bool hasIdentityCard = true;
if (age >= 18) {
if (hasIdentityCard) {
std::cout << "Entry allowed.\n";
} else {
std::cout << "Please provide an identity card.\n";
}
} else {
std::cout << "You do not meet the age requirement.\n";
}Output
Entry allowed.Nested conditions are useful when one decision depends on another. Keep nesting shallow when possible so the code remains easy to follow.
Relational and logical operators help you build conditions.
| Operator | Meaning | Example | ||||
|---|---|---|---|---|---|---|
== | Equal to | score == 100 | ||||
!= | Not equal to | choice != 0 | ||||
> | Greater than | age > 18 | ||||
< | Less than | temperature < 10 | ||||
>= | Greater than or equal to | marks >= 40 | ||||
<= | Less than or equal to | quantity <= 5 | ||||
&& | Logical AND: both conditions must be true | age >= 18 && hasTicket | ||||
| ` | ` | Logical OR: at least one condition must be true | `isWeekend | isHoliday` | ||
! | Logical NOT: reverses a Boolean value | !isLoggedIn |
Example
int age = 25;
bool hasTicket = true;
if (age >= 18 && hasTicket) {
std::cout << "You can enter the event.\n";
}
Both conditions must be true for the message to appear.
C++ uses short-circuit evaluation for && and ||. It evaluates the second operand only when needed to determine the result.
A switch statement selects a branch by comparing an expression with constant case values. It is useful for menus and fixed choices.
Example
int choice = 2;
switch (choice) {
case 1:
std::cout << "Start a new game.\n";
break;
case 2:
std::cout << "Load a saved game.\n";
break;
case 3:
std::cout << "Exit the game.\n";
break;
default:
std::cout << "Invalid choice.\n";
}
Output
Load a saved game.
The main parts are:
switch: Evaluates the expression used to select a branch.case: Identifies a constant value that can match the expression.break: Exits the switch.default: Handles values that do not match any case.
A switch condition must have an integral or enumeration type, or a class type convertible to one. Beginner examples commonly use int, char, or an enumeration. You cannot directly switch on a std::string or a floating-point value.
Fallthrough Between Cases
Without a break or another statement that transfers control, execution continues into the following case.
int value = 1;
switch (value) {
case 1:
std::cout << "One\n";
case 2:
std::cout << "Two\n";
break;
}
Output
One
Two
This behavior is called fallthrough. Usually, each independent case should end with break.
The conditional operator chooses between two expressions. It is useful for short decisions that produce a value.
Syntax
condition ? expressionIfTrue : expressionIfFalse
Example
int first = 12;
int second = 20;
int larger = (first > second) ? first : second;
std::cout << "Larger number: " << larger << '\n';
Output
Larger number: 20
Use if...else when each branch requires several statements or when it makes the code easier to read.
Loops repeat a statement or block of statements.
C++ provides three traditional loop forms:
forwhiledo...while
It also provides a range-based for loop for iterating over elements.
The for Loop
A for loop is useful when a counter controls repetition.
Syntax
for (initialization; condition; update) {
// Repeated statements.
}Example
for (int i = 1; i <= 5; ++i) {
std::cout << i << ' ';
}Output
1 2 3 4 5The loop works as follows:
int i = 1runs once.i <= 5is checked before each iteration.- The loop body runs if the condition is true.
++iincreases the counter.- The process repeats until the condition becomes false.
The while Loop
A while loop checks its condition before each iteration.
Syntax
while (condition) {
// Repeated statements.
}Example
int count = 3;
while (count > 0) {
std::cout << count << ' ';
--count;
}Output
3 2 1If the condition is false at the beginning, the loop body does not execute.
The do...while Loop
A do...while loop checks its condition after executing the body. Therefore, its body always runs at least once.
Syntax
do {
// Repeated statements.
} while (condition);Notice the semicolon after the closing condition.
Example
int number = 10;
do {
std::cout << number << '\n';
++number;
} while (number < 5);Output
10The body executes once even though number < 5 is false.
Comparing Loop Types
| Loop | Condition checked | Minimum executions | Common use |
|---|---|---|---|
for | Before the body | 0 | Counter-controlled repetition |
while | Before the body | 0 | Repetition controlled by a condition |
do...while | After the body | 1 | Actions that must happen at least once |
The Range-Based for Loop
A range-based for loop, available since C++11, visits the elements of an array or another supported range.
int scores[] = {75, 82, 90, 68};
for (int score : scores) {
std::cout << score << ' ';
}Output
75 82 90 68Here, score receives a copy of each element. Use a reference when you want to modify the original elements:
for (int& score : scores) {
score += 5;
}After this loop, the array contains 80, 87, 95, and 73.
A loop inside another loop is called a nested loop. Nested loops are useful for working with grids, tables, and patterns.
Example
for (int row = 1; row <= 3; ++row) {
for (int column = 1; column <= 4; ++column) {
std::cout << "* ";
}
std::cout << '\n';
}
Output
* * * *
* * * *
* * * *
The outer loop controls the rows. For every row, the inner loop prints four stars.
Jump statements transfer control away from the normal execution path.
The break Statement
The break statement exits the nearest enclosing loop or switch.
for (int i = 1; i <= 10; ++i) {
if (i == 5) {
break;
}
std::cout << i << ' ';
}
Output
1 2 3 4
In nested loops, break exits only the innermost loop containing it.
The continue Statement
The continue statement skips the remaining statements in the current loop iteration.
for (int i = 1; i <= 5; ++i) {
if (i == 3) {
continue;
}
std::cout << i << ' ';
}
Output
1 2 4 5
In a for loop, control moves to the update expression before checking the condition again. In a while loop, control moves directly to the condition.
The return Statement
The return statement ends the current function and can send a value back to its caller.
bool isPositive(int number) {
if (number > 0) {
return true;
}
return false;
}
When either return executes, the function ends immediately.
The goto Statement
C++ also provides goto, which transfers control to a labeled statement within the same function.
For ordinary decisions and repetition, prefer conditional statements, loops, and functions. Excessive use of goto can make execution paths difficult to follow.
The following program combines input, a loop, conditional statements, break, and continue.
The user can enter positive integers to add to a total, negative integers to skip, and 0 to stop.
#include <iostream>
int main() {
int number;
long long total = 0;
std::cout << "Enter integers (0 to stop).\n";
while (std::cin >> number) {
if (number == 0) {
break;
}
if (number < 0) {
std::cout << "Negative number skipped.\n";
continue;
}
total += number;
}
std::cout << "Total: " << total << '\n';
return 0;
}
Example Run
Enter integers (0 to stop).
10
-3
Negative number skipped.
20
0
Total: 30
The expression std::cin >> number attempts to read an integer. The loop continues while input succeeds, so it also stops if the user enters invalid input or the input ends.
Using = Instead of ==
= assigns a value. == compares two values.
// Incorrect when the intention is to compare:
if (number = 5) {
std::cout << "Matched\n";
}
// Correct:
if (number == 5) {
std::cout << "Matched\n";
}
The first condition assigns 5 to number. That nonzero value then converts to true.
Adding an Unwanted Semicolon
// Incorrect:
if (number > 0);
{
std::cout << "Positive\n";
}
The semicolon ends the if statement with an empty body. The following block executes regardless of the condition.
Forgetting to Update a Loop Variable
int i = 1;
while (i <= 5) {
std::cout << i << ' ';
// Missing ++i.
}
Because i never changes, the condition stays true and the loop keeps running.
Making an Off-by-One Error
An array with five elements has valid indexes from 0 to 4.
int values[] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; ++i) {
std::cout << values[i] << ' ';
}
Using i <= 5 would attempt to access an element outside the array, causing undefined behavior.
Writing Chained Comparisons
Do not use mathematical comparison chains to check a range.
// Incorrect:
if (0 < number < 10) {
// Does not check the intended range.
}
// Correct:
if (number > 0 && number < 10) {
std::cout << "The number is between 0 and 10.\n";
}- Use braces around conditional and loop bodies, even when they contain one statement.
- Indent code consistently to make nesting clear.
- Choose conditions that are easy to understand.
- Use a range-based
forloop when you only need to visit elements. - Check loop boundaries carefully.
- Ensure a loop can reach its stopping condition.
- Avoid deeply nested logic when a simpler structure is available.
- Write a program that checks whether an integer is positive, negative, or zero.
- Use
if...elseto find the largest of three numbers. - Create a calculator that uses
switchto select addition, subtraction, multiplication, or division. Handle division by zero. - Use a
forloop to print the multiplication table of a given number. - Use a
whileloop to calculate the sum of the digits of a positive integer. - Use nested loops to print a right-angled triangle of stars.
- Print the numbers from 1 to 20, skipping multiples of 3 with
continue.
Control structures make C++ programs capable of choosing actions and repeating work. Conditional statements select a path, loops repeat statements, and jump statements change execution flow. Understanding these tools prepares you to build programs that handle input, process collections, and solve problems step by step.