Published: December 7, 2025
Reading Time: 9 minutes
This comprehensive guide to control structures in C++ provides:
When writing code, programs often need to repeat particular functions or actions based on certain conditions and parameters at each step. Similar to recipes where water might be added when ingredients get too dry, or cooking time extended when food is still raw, coding uses control structures to decide the flow or structure of a program based on conditions.
Control structures in C++ are the building blocks that help make code flow smooth and more functional. They enable decision-making, changing the sequence of particular actions based on given conditions, or repeating actions when necessary.
Based on the logic used to make decisions, there are three different types of control structures in C++.
The sequence control structure in C++ is based on sequential flow of logic. The program executes in the exact order of instructions as provided by the user in sequential order. It is the simplest control structure, based on simple logic. No additional decision-making is involved. Execution is done linearly in a line-by-line manner, even for complex problems.
#include <iostream>
using namespace std;
int main() {
cout << "This is the first statement." << endl;
cout << "This is the second statement." << endl;
cout << "This is the third statement." << endl;
return 0;
}
This is the first statement.
This is the second statement.
This is the third statement.
The program follows a linear approach, executing each instruction one by one. The statements are output in order: first, second, and third statements.
The selection, or conditional control structure in C++, is about making choices based on conditions. For instance, to say "hello" only when the user is female, and say "bye" when the user is male, a conditional statement makes that choice.
#include <iostream>
using namespace std;
int main() {
char gender;
// Taking user input for gender
cout << "Enter your gender (M/F): ";
cin >> gender;
// Selection control structure (if-else)
if (gender == 'F' || gender == 'f') {
cout << "Hello" << endl;
} else if (gender == 'M' || gender == 'm') {
cout << "Bye" << endl;
} else {
cout << "Invalid input!" << endl;
}
return 0;
}
Enter your gender (M/F): F
Hello
Enter your gender (M/F): M
Bye
The program asks the user for their gender. The input is processed through an if-else block, where "hello" is provided for female gender and "bye" is provided for male gender.
#include <iostream>
using namespace std;
int main() {
int marks;
// Taking user input
cout << "Enter your marks (0-100): ";
cin >> marks;
// Multi-alternative if-else statement to determine grades
if (marks >= 90) {
cout << "Grade: A" << endl;
} else if (marks >= 80) {
cout << "Grade: B" << endl;
} else if (marks >= 70) {
cout << "Grade: C" << endl;
} else if (marks >= 60) {
cout << "Grade: D" << endl;
} else {
cout << "Grade: F (Fail)" << endl;
}
return 0;
}
Enter your marks (0-100): 85
Grade: B
Enter your marks (0-100): 45
Grade: F (Fail)
The iteration control structure in C++ is based on loops. Loops are repetitive statements used to execute the same body of instructions multiple times until a particular condition is fulfilled. This is useful when performing the same task multiple times based on a condition.
#include <iostream>
using namespace std;
int main() {
// Using a for loop to print numbers from 1 to 10
for (int i = 1; i <= 10; i++) {
cout << i << " ";
}
return 0;
}
1 2 3 4 5 6 7 8 9 10
The loop initializes with i=1 and prints i at the end of each iteration. It increases the value of i by 1 before the next iteration, checks whether i is less than or equal to 10, and continues the process until the value of i reaches 10.
To implement control structures, specific control statements are needed. These statements are discussed in detail below.
If a specified condition is true, the if statement runs a block of code. It is called a conditional statement, and it checks if a given condition is true. Based on the condition, it proceeds to certain statements.
if [condition to be checked] {
// Statements to run.
}
#include <iostream>
using namespace std;
int main() {
int num;
// Taking user input
cout << "Enter a number: ";
cin >> num;
// Simple if statement to check if number is positive
if (num > 0) {
cout << "The number is positive." << endl;
}
return 0;
}
In this example, the code inside the if block runs only if the number is positive.
The if-else statement is also a conditional statement. It works like the if statement, with the addition of providing an additional statement to run in case the condition is false.
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
#include <iostream>
using namespace std;
int main() {
int num;
// Taking user input
cout << "Enter a number: ";
cin >> num;
// If-else statement to check if the number is positive or negative
if (num > 0) {
cout << "The number is positive." << endl;
} else {
cout << "The number is negative or zero." << endl;
}
return 0;
}
Enter a number: -3
The number is negative or zero.
Enter a number: 5
The number is positive.
In this example, the code inside the if block is executed if the number is positive. If not, the else block's function is executed.
The if-else-if ladder is an extension of the if-else statement that allows multiple conditions to be checked in order. It is useful when there are multiple possible outcomes, and only one needs to be executed. The program evaluates each condition from top to bottom, and once a true condition is found, that particular block is executed, and the rest are skipped.
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else if (condition3) {
// code to be executed if condition3 is true
} else {
// code to be executed if none of the conditions are true
}
#include <iostream>
using namespace std;
int main() {
int num;
// Taking user input
cout << "Enter a number: ";
cin >> num;
// If-else-if ladder to classify the number
if (num > 0) {
cout << "The number is positive." << endl;
} else if (num < 0) {
cout << "The number is negative." << endl;
} else {
cout << "The number is zero." << endl;
}
return 0;
}
Enter a number: -3
The number is negative.
Enter a number: 5
The number is positive.
Enter a number: 0
The number is zero.
The program first checks if the number is positive. If the condition is false, it moves to the next block to check if the number is negative. If that condition is also false, the final else block executes, indicating the number is zero.
If a particular condition may have many possible outputs, writing multiple if-else statements becomes tedious. The switch statement provides multiple code blocks that can be executed in different cases. There is a default code block that is executed in case the condition does not match any of the other cases.
switch (expression) {
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
...
default:
// code to be executed if expression doesn't match any case
}
#include <iostream>
using namespace std;
int main() {
int day;
// Taking user input
cout << "Enter a number (1-7) for the day of the week: ";
cin >> day;
// Switch statement to determine the day
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 input! Please enter a number between 1 and 7." << endl;
}
return 0;
}
Enter a number (1-7) for the day of the week: 3
Wednesday
| Feature | If-else Statement | Switch Statement |
|---|---|---|
| Usage | Used for evaluating multiple conditions involving relational, logical, or equality operators | Used when multiple values of a single variable need to be compared |
| Flow | Checks conditions sequentially; once a condition is true, it executes the corresponding block and skips the rest | Executes the matching case directly, hence more efficient |
| Efficiency | Can be slower when there are many conditions since it checks conditions one by one | Generally faster when handling multiple constant values |
| Readability | Can become difficult to read when there are too many conditions | Easier to read and manage when dealing with multiple fixed values |
| Default Case | The else block executes when no conditions are met | The default case executes when no matching case values are found |
There are occasions in programs where a particular group of instructions needs to be executed multiple times. In C++, there are three kinds of loop statements for this purpose.
The for iterative loop is used when the exact number of times a block of code needs to be executed is known. It is useful for repetitive tasks such as printing numbers from 1-10 or calculating the sum of the first 10 numbers. Initialization, condition, and increment/decrement are all part of the same line. The condition is defined such that the loop code runs for a specified number of times only, until the condition is satisfied.
#include <iostream>
using namespace std;
int main() {
// Using a for loop to print numbers from 1 to 5
for (int f = 1; f <= 5; f++) {
cout << f << " ";
}
return 0;
}
1 2 3 4 5
int f = 1; The loop starts with f = 1f <= 5; Runs as long as f is less than or equal to 5f++; Increases f by 1 in each iterationcout << f << " "; prints numbers from 1 to 5 on the same lineThe while loop is used when the number of iterations isn't specifically known for a code block to run. It checks the condition every time before running the loop, and if it is true, it runs the code; otherwise if it is false, it skips it.
#include <iostream>
using namespace std;
int main() {
int e = 1; // Initialization
// While loop to print numbers from 1 to 5
while (e <= 5) {
cout << e << " ";
e++; // Increment
}
return 0;
}
1 2 3 4 5
int e = 1; The loop starts with e = 1while (e <= 5); Runs as long as e is less than or equal to 5cout << e << " "; prints e in each iteratione++; increases e by 1 in every iterationSimilar to a while loop, the do-while loop operates as well. The only distinction is that the condition is checked after each time the loop is executed. This ensures that, even if the condition is never met, the function inside the loop executes at least once.
#include <iostream>
using namespace std;
int main() {
int num;
// Do-while loop for user input validation
do {
cout << "Enter a positive number: ";
cin >> num;
} while (num <= 0);
cout << "You entered: " << num << endl;
return 0;
}
Enter a positive number: -5
Enter a positive number: 0
Enter a positive number: 7
You entered: 7
The loop runs once, and the while statement checks the condition after every run and keeps repeating the loop until the user inputs a positive number.
Jump statements are used to 'jump out' of a running block of code. It can be an iterative or conditional block. A jump statement stops the block from running and moves on to the next part of the code.
#include <iostream>
#include <cstdlib> // Required for exit()
using namespace std;
int main() {
// Demonstrating break
cout << "Break statement example:" << endl;
for (int i = 1; i <= 5; i++) {
if (i == 3) {
cout << "Breaking out of loop at i = " << i << endl;
break; // Exits the loop when i == 3
}
cout << "i = " << i << endl;
}
// Demonstrating continue
cout << "\nContinue statement example:" << endl;
for (int i = 1; i <= 5; i++) {
if (i == 3) {
cout << "Skipping iteration at i = " << i << endl;
continue; // Skips the rest of the loop body for i == 3
}
cout << "i = " << i << endl;
}
// Demonstrating goto
cout << "\nGoto statement example:" << endl;
int num;
cout << "Enter a positive number: ";
cin >> num;
if (num < 0) {
goto negative; // Jumps to the label if the number is negative
}
cout << "You entered: " << num << " (Valid Input)" << endl;
goto end; // Skips the negative label message
negative:
cout << "Error: Negative number entered!" << endl;
end:
cout << "\nExiting goto demonstration." << endl;
// Demonstrating exit()
cout << "\nExit statement example:" << endl;
cout << "Exiting the program with exit code 0." << endl;
exit(0); // Terminates the program immediately
// This line will never execute due to exit()
cout << "This statement will not be printed!" << endl;
return 0;
}
Break statement example:
i = 1
i = 2
Breaking out of loop at i = 3
Continue statement example:
i = 1
i = 2
Skipping iteration at i = 3
i = 4
i = 5
Goto statement example:
Enter a positive number: -5
Error: Negative number entered!
Exiting goto demonstration.
Exit statement example:
Exiting the program with exit code 0.
Together, these loops automate repetitive tasks and improve code efficiency.
All control statements run based on the evaluation of some condition. The code is executed based on whether the condition is true or false, and hence these true and false values are very important in control structure in C++. C++ has a built-in data type bool, which is made to store the values true or false. All statements are internally evaluated as booleans only. 0 is evaluated as false and 1 or any non-zero value is evaluated as true.
#include <iostream>
using namespace std;
int main() {
bool isSunny = true; // Boolean variable storing true
if (isSunny) {
cout << "It is a sunny day!" << endl;
} else {
cout << "It is not sunny today." << endl;
}
int number;
cout << "Enter a number: ";
cin >> number;
if (number) { // Non-zero numbers are evaluated as true
cout << "You entered a non-zero value, which is considered true." << endl;
} else {
cout << "You entered zero, which is considered false." << endl;
}
return 0;
}
It is a sunny day!
Enter a number: 5
You entered a non-zero value, which is considered true.
It is a sunny day!
Enter a number: 0
You entered zero, which is considered false.
The bool variable isSunny holds true, so the first if condition executes.
When the user enters a number, it is converted to bool:
bool to represent true or false, forming the backbone of all condition checksLogical and conditional operators are essential tools in C++ that allow programs to make decisions based on one or more conditions. They help control the flow of execution by evaluating expressions and determining which code blocks should run.
Sometimes complex conditions need to be evaluated for a control statement. There may be a combination of multiple conditions whose output needs to be evaluated in order to process the control statement. Logical operators enable this smooth evaluation.
It is a binary operator (needs two inputs). It returns true if both statements/conditions are true, otherwise it returns false.
[condition1 && condition2]
| Condition 1 | Condition 2 | Result |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
#include <iostream>
using namespace std;
int main() {
int num;
// Taking user input
cout << "Enter a number: ";
cin >> num;
// Using the AND (&&) operator to check if the number is positive and even
if (num > 0 && num % 2 == 0) {
cout << "The number is positive and even." << endl;
} else {
cout << "The condition is not met." << endl;
}
return 0;
}
Enter a number: 8
The number is positive and even.
Enter a number: -4
The condition is not met.
Enter a number: 5
The condition is not met.
The program asks the user to enter a number. The if condition uses the AND (&&) operator, meaning both conditions must be true:
num > 0: The number must be positivenum % 2 == 0: The number must be evenIf both conditions are true, it prints "The number is positive and even." Otherwise, it prints "The condition is not met."
This is also a binary operator. It returns true if even one of the conditions is true.
[condition1 || condition2]
| Condition 1 | Condition 2 | Result |
|---|---|---|
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
#include <iostream>
using namespace std;
int main() {
int num;
// Taking user input
cout << "Enter a number: ";
cin >> num;
// Using the OR (||) operator
if (num < 0 || num % 2 == 0) {
cout << "The number is either negative or even." << endl;
} else {
cout << "The number is positive and odd." << endl;
}
return 0;
}
Enter a number: -3
The number is either negative or even.
Enter a number: 6
The number is either negative or even.
Enter a number: 5
The number is positive and odd.
The || (OR) operator returns true if at least one condition is true:
num < 0: The number is negativenum % 2 == 0: The number is evenIf either condition is true, the program prints "The number is either negative or even." Otherwise, it prints "The number is positive and odd."
This is a unary operator, meaning it only requires a single input. It reverses the value of whatever input is provided to it. True becomes false and false becomes true.
[!condition]
| Condition | Result |
|---|---|
| true | false |
| false | true |
#include <iostream>
using namespace std;
int main() {
int num;
// Taking user input
cout << "Enter a number: ";
cin >> num;
// Using the NOT (!) operator
if (!(num > 0)) {
cout << "The number is not positive." << endl;
} else {
cout << "The number is positive." << endl;
}
return 0;
}
Enter a number: -5
The number is not positive.
Enter a number: 0
The number is not positive.
Enter a number: 3
The number is positive.
The ! (NOT) operator reverses the condition:
!(num > 0) means if the number is NOT positive (i.e., 0 or negative)The conditional operator, or the ternary operator (? :), is a brief manner of writing a simple if-else logic. It checks a condition and yields one of two values depending on whether the condition is true or false.
(condition) ? expression1 : expression2
#include <iostream>
using namespace std;
int main() {
int num;
// Taking user input
cout << "Enter a number: ";
cin >> num;
// Ternary operator to check even or odd
string result = (num % 2 == 0) ? "Even" : "Odd";
cout << "The number is " << result << "." << endl;
return 0;
}
Enter a number: 8
The number is Even.
Enter a number: 5
The number is Odd.
The ternary operator condition ? true_value : false_value works as:
num % 2 == 0 (i.e., the number is even), the result is set to "Even"The result is printed to the screen.
Use the conditional operator in cases of simple assignments or expressions when a full if-else statement is just too long and unnecessarily verbose. If your logic is complicated or you have multiple statements, then use if-else blocks for better understanding.
It is possible to combine logical operators inside the conditional (ternary) operator in order to have compact, expressive decision logic.
string result = (num > 0 && num % 2 == 0)
? "Positive and even"
: "Not positive and even";
Logical operators (&&, ||, !) give the opportunity to create complex conditions by combining simple expressions. The conditional (ternary) operator (? :) is a shorthand for simple decision-making. Combined, they offer great flexibility and readability in controlling the program flow based on multiple criteria.
In C++, error handling is done using exception handling control structures like try, catch, and throw. These structures allow a program to handle runtime errors instead of crashing.
If a program attempts to divide a number by zero, an exception can be thrown.
#include <iostream>
using namespace std;
int main() {
try {
int a = 10, b = 0;
if (b == 0)
throw "Division by zero error!";
cout << a / b << endl;
} catch (const char* msg) {
cout << "Error: " << msg << endl;
}
return 0;
}
If an invalid index is accessed in an array, an exception can be thrown.
#include <iostream>
using namespace std;
int main() {
try {
int arr[3] = {1, 2, 3};
int index = 5; // Invalid index
if (index >= 3)
throw out_of_range("Array index out of bounds!");
cout << arr[index] << endl;
} catch (out_of_range& e) {
cout << "Exception: " << e.what() << endl;
}
return 0;
}
If a file cannot be opened, an exception is thrown.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
try {
ifstream file("non_existent.txt");
if (!file)
throw runtime_error("File not found!");
cout << "File opened successfully!" << endl;
} catch (runtime_error& e) {
cout << "Exception: " << e.what() << endl;
}
return 0;
}
Control structures in C++ play a fundamental role in defining the flow of execution in a program. They allow programs to make decisions, repeat tasks, and manage the logic of code efficiently. By understanding the three main types—sequential, selection, and iteration control structures—programmers can write more structured and efficient programs. Control statements like if-else, switch, loops, and logical operators help implement these structures effectively. Mastering these concepts is important for writing smooth and well-structured C++ programs.
Control structures in C++ regulate how a program is executed, enabling looping and decision-making. They are crucial for controlling the sequence in which assertions are carried out according to particular repetitions or circumstances.
Control structures in C++ are categorized into three main types:
While a while loop only executes if its condition is true, a do-while loop executes at least once, and then it checks its condition.
The switch statement evaluates an expression and executes the corresponding case block that matches the expression's value. If no match is found, the default block is executed.
The break statement immediately terminates the nearest loop or switch statement, transferring to the statement following the terminated one.
To break out of a loop before it ends, use the break statement.
The continue statement moves on to the next iteration of a loop by omitting the remaining code in the current iteration.
Source: NxtWave - CCBP Blog
Original URL: https://www.ccbp.in/blog/articles/control-structures-in-cpp
Published: December 7, 2025