When we are writing code, we often need to repeat a particular function or action based on certain conditions and parameters at each step. Like in different recipes, we may need to add water based on the condition that it’s getting too dry, or cook it for longer based on the fact that it is still a bit raw. Similarly, we do so in coding also. In order to decide the flow or structure of a program based on conditions, we use control structure in C++. These control structures are of different types, each of which we will explore in detail:
- Decision control structure in C++
- Conditional control structure in C++
- Iteration control structure in C++
- Sequence control structure in C++
- Jumping control structure in C++
These control structures act as the building blocks of our code, helping in making the flow smooth and more functional. They help by making decisions, changing the sequence of particular actions based on some given conditions, or even repeating actions when necessary. Let us explore how we can implement control structure in C++ as well as how many such types of control structures exist in C++.
Based on the logic being used to make decisions, we have three different types of control structures in C++.
1. Sequence Control Structure in C++
As understood by the name, the sequence control structure in c++ is based on sequential flow of logic. It means that the program will be executed in the exact order of instructions as provided by the user in sequential order. It is the simplest control structure, based on simple logic that we write. No additional decision making is involved in this. Execution is done linearly in a line-by-line manner, even for complex problems.
Code
#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;
}
Output
This is the first statement.
This is the second statement.
This is the third statement.
Explanation
We can see here that our program followed a linear approach, executing each instruction one by one. Hence we get the statements in order; first, second and third statements.
2. Selection Control Structure in C++
The selection, or conditional control structure in C++ is about making choices based on conditions. For instance, if we want to say "hello" only when the user is female, and say "bye" when the user is male, we use a conditional statement to make that choice. Let’s look at an example to make it clearer.
Code
#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;
}
Output
Enter your gender (M/F): F
Hello
Enter your gender (M/F): M
Bye
Explanation
We are first asking the user for their gender. The input is then read and processed through an if-else block, where out “hello” is provided for the female gender and the output “bye” is provided if the input is male gender.
In selection control structure in C++, we have two types of selection control statements:
- If-Else statement
- Switch statement
Example with Multiple Alternatives
For multiple alternatives, we use an if-else ladder as demonstrated in this code.
Code
#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;
}
Output
Enter your marks (0-100): 85
Grade: B
Enter your marks (0-100): 45
Grade: F (Fail)
We will explore these control statements in more detail in a later section.
3. Iteration Control Structure in C++
This iteration control structure in C++ is based on loops. Loops are a repetitive statement used to execute the same body of instructions multiple times until a particular condition is fulfilled. It is useful when we need to perform the same task multiple times based on a condition.
Code
#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;
}
Output
1 2 3 4 5 6 7 8 9 10
Explanation
The loop initialises with i=1 and prints i at the end of each iteration. It increases the value of i by 1 before the next iteration and checks whether i is less than 10 or not, and continues the process until the value of i reaches 10.
We have three types of loops in C++:
- For loop
- While loop
- Do-while loop
We will explore all of them in more detail later on.
In order to implement the control structures we read about, we need some control statements. These statements are discussed in detail below.
1. if Statement
The if statement executes a block of code if a given condition is true. It is called a conditional statement, and it checks if a given condition is true. Based on the condition, it proceeds to certain statements.
Syntax
if [condition to be checked] {
// Statements to run.
}
Code Example
#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.
2. if-else Statement
The if-else statement is also a conditional statement. It works just like the if statement, the only addition is that it provides an additional statement to run in case the condition is false.
Syntax
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Code Example
#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;
}
Sample Output
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. Otherwise, the code in the else block is executed.
3. if-else-if ladder
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 of them 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.
Syntax
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 condition1 is true
} else {
// code to be executed if none of the conditions are true
}
Code Example
#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;
}
Sample Output
Enter a number: -3
The number is negative.
Enter a number: 5
The number is positive.
Enter a number: 0
The number is zero.
In this example, the program first checks if the number is positive. If the condition is false, it moves to the next block check to see if the number is negative. If that condition is also false, the final else block executes, indicating the number is zero.
4. switch Statement
If a particular condition may have many possible outputs, writing multiple if-else statements becomes tedious. So we can use the switch statement instead, which 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.
Syntax
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
}
Code Example
#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;
}
Sample Output
Enter a number (1-7) for the day of the week: 3
Wednesday
Explanation
The program asks the user to enter a number from 1 to 7.
The switch statement checks the value of day and prints the corresponding weekday.
The break statement ensures only the correct case executes.
If the user enters a number outside 1-7, the default case runs and prints "Invalid input!".
Differences between if-else and switch statements
As mentioned earlier, there are occasions in our program where we may need to execute a particular group of instructions multiple times. In C++, we have three kinds of loop statements for this purpose:
1. For loop
We can use the for iterative loop when we know precisely how many times a block of code is to be executed. 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.
Code Example
#include <iostream>
using namespace std;
int main() {
// Using a for loop to print numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
return 0;
}
Sample Output
1 2 3 4 5
Explanation
Initialization: int i = 1; The loop starts with i = 1.
Condition: i <= 5; Runs as long as i is less than or equal to 5.
Increment: i++; Increases i by 1 in each iteration.
Prints Numbers: cout << i << " "; prints numbers from 1 to 5 on the same line.
2. While loop
We use a while loop 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.
Code Example
#include <iostream>
using namespace std;
int main() {
int i = 1; // Initialization
// While loop to print numbers from 1 to 5
while (i <= 5) {
cout << i << " ";
i++; // Increment
}
return 0;
}
Output
1 2 3 4 5
Explanation
Initialization: int i = 1; The loop starts with i = 1.
Condition: while (i <= 5); Runs as long as i is less than or equal to 5.
Execution: cout << i << " "; prints i in each iteration.
Increment: i++; increases i by 1 in every iteration.
3. Do-while loop
The do-while loop works exactly like a while loop. The only difference is that it checks the condition after running the loop every time. This makes sure that the code inside the loop runs at least once, even if the condition never becomes true.
Code Example
#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;
}
Output
Enter a positive number: -5
Enter a positive number: 0
Enter a positive number: 7
You entered: 7
Explanation
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.
4. Jump statements
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.
The different kinds of jump statements in C++ are:
- Break: jumps out of the entire block of code and moves to the part of the program outside the code block.
- Continue: jumps out of that particular iteration of the block and moves on to the next iteration.
- Goto: jumps from the current position in the program to another, specified by a user defined label.
- exit(): the exit statement jumps out of the current program with a specific exit code.
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;
}
Sample Output
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.
Explanation
- break Statement: Used inside a loop to immediately stop execution and exit the loop when i == 3.
- continue Statement: Skips the rest of the loop body for i == 3 and moves to the next iteration.
- goto Statement: Jumps to the negative label if a negative number is entered. Skips the error message when a valid number is provided.
- exit() Statement: Immediately terminates the program with an exit code of 0, preventing further execution.
All the 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 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.
Code
#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;
}
Sample Output
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.
Explanation
The bool variable isSunny holds true, so the first if condition executes.
When the user enters a number, it is converted to bool:
- If it is non-zero: true
- If it is 0: false
Sometimes we may need to evaluate more complex conditions 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. In order to do this smoothly, we have the logical operators. The three kinds of logical operators in C++ are explained below:
1. Logical AND (&&)
It is a binary operator (needs two inputs). It returns true if both statements/conditions are true, otherwise it returns false.
Syntax
[condition1 && condition2]
Truth table
Example Code
#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;
}
Sample Output
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.
Explanation
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 positive.
- num % 2 == 0 : The number must be even.
If both conditions are true, it prints "The number is positive and even."
Otherwise, it prints "The condition is not met."
2. Logical OR (||)
This is also a binary operator. It returns true if even one of the conditions is true.
Syntax
[condition1 || condition2]
Truth Table
Example Code
#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;
}
Sample Output
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.
Explanation
The || (OR) operator returns true if at least one condition is true:
- num < 0 : The number is negative.
- num % 2 == 0 : The number is even.
If either condition is true, the program prints "The number is either negative or even."
Otherwise, it prints "The number is positive and odd."
3. Logical NOT (!)
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.
Syntax
[!condition]
Truth Table
Example Code
#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;
}
Sample Output
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.
Explanation
The ! (NOT) operator reverses the condition:
- !(num > 0) means if the number is NOT positive (i.e., 0 or negative).
- If num is not positive, it prints "The number is not positive."
- Otherwise, it prints "The number is positive."
The conditional operator is also known as the ternary operator. It is a shorter way of writing the if else statement. We can assign a value to a variable based on a condition using this operator.
Syntax
(condition) ? expression1 : expression2
Example
#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;
}
Sample Output
Enter a number: 8
The number is Even.
Enter a number: 5
The number is Odd.
Explanation
The ternary operator condition ? true_value : false_value works as:
- If num % 2 == 0 (i.e., the number is even), the result is set to "Even".
- Otherwise, the result is set to "Odd".
The result is printed to the screen.
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.
- try block: The code that might cause an exception is placed inside a try block.
- throw statement: If an error occurs, a throw statement is used to signal an exception.
- catch block: This block catches the exception thrown and handles it.
Types of Errors and How to Handle Them
1. Divide by Zero (Arithmetic Error)
If a program attempts to divide a number by zero, an exception can be thrown.
Code
#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;
}
2. Array Index error
If an invalid index is accessed in an array, an exception can be thrown.
Code
#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;
}
3. File Handling Error
If a file cannot be opened, an exception is thrown.
Code
#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 us to make decisions, repeat tasks, and manage the logic of our code efficiently. By understanding the three main types—sequential, selection, and iteration control structures—we 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.
1. What is a control structure in C++?
In C++, control structures manage the flow of a program's execution, allowing for decision-making and looping. They are essential for directing the order in which statements are executed based on specific conditions or repetitions.
2. Explain control structures in C++.
Control structures in C++ are categorized into three main types:
- Sequential Control Structure: Executes statements in the order they appear.
- Selection Control Structure: Uses conditional statements like if, else if, else, and switch to execute code blocks based on specific conditions.
- Iteration Control Structure: Employs loops such as for, while, and do-while to repeat code blocks until certain conditions are met.
3. What is the difference between while and do-while loops in C++?
A while loop checks its condition before executing the loop's body, whereas a do-while loop checks its condition after executing the loop's body at least once.
4. How does the switch statement work in C++?
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.
5. What is the purpose of the break statement in loops?
The break statement immediately terminates the nearest loop or switch statement, transferring to the statement following the terminated one.
6. How can I exit a loop in C++?
You can use the break statement to exit a loop before its termination.
7. What is the role of the continue statement in loop control?
The continue statement skips the remaining code in the current iteration of a loop and proceeds with the next iteration.