In computer programming, control structures are essential elements that allow you to control the flow of your program's execution. They help you to make decisions, repeat actions, & alter the sequence of instructions based on certain conditions. Control structures in C++ provide the foundation for creating logical & efficient programs.
In this article, we will talk about the different types of control structures available in C++, understand how they work & their examples.
Types of Control Structure in C++
In C++, there are three main types of control structures: sequential, selection, & iteration.
Sequential Control Structure
The sequential control structure is the most basic type. It executes instructions one after another in a linear fashion. Each statement is executed in the order they appear in the program. Here's a simple example:
C++
C++
#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;
}
You can also try this code with Online C++ Compiler
This is the first statement.
This is the second statement.
This is the third statement.
In this example, the statements are executed sequentially, starting from the first cout statement & progressing to the next until the end of the program.
Selection Control Structure:
The selection control structure allows you to make decisions based on certain conditions. It enables your program to execute different blocks of code depending on whether a condition is true or false. The two main selection control structures in C++ are:
a. if statement
b. switch statement
Example :
C++
C++
#include <iostream> using namespace std;
int main(){
int number = 5;
if (number > 0) {
cout << "Positive number";
} else {
cout << "Non-positive number";
}
return 0; }
You can also try this code with Online C++ Compiler
The iteration control structure, also known as loops, allows you to repeat a block of code multiple times based on a condition. It is useful when you need to perform a task repeatedly until a specific condition is met. The three main iteration control structures in C++ are:
a. for loop
b. while loop
c. do-while loop
Example
C++
C++
#include <iostream> using namespace std; int main() {
for(int i = 1; i <= 5; i++) {
cout << i << " ";
}
return 0;
}
You can also try this code with Online C++ Compiler
In this example, the code inside the if block will only execute if the condition age >= 18 is true.
if-else statement
The if-else statement extends the if statement by providing an alternative block of code to execute if the condition is false. It has the following syntax:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Example
C++
C++
#include <iostream> using namespace std; int main() {
cppCopy codeint number = 7;
if (number % 2 == 0) {
cout << "The number is even." << endl;
} else {
cout << "The number is odd." << endl;
}
return 0; }
You can also try this code with Online C++ Compiler
In this example, if the condition number % 2 == 0 is true, the code inside the if block will execute, otherwise, the code inside the else block will execute.
switch statement
The switch statement allows you to select one of many code blocks to be executed based on the value of a variable or expression. It provides a cleaner & more efficient alternative to using multiple if-else statements. The syntax is as follows:
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
}
Example:
C++
C++
#include <iostream> using namespace std; int main() {
int dayNumber = 3;
switch (dayNumber) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
...
default:
cout << "Invalid day number" << endl;
}
return 0; }
You can also try this code with Online C++ Compiler
In this example, based on the value of dayNumber, the corresponding case block will be executed. If none of the cases match, the code inside the default block will be executed.
for Loop
Perfect for when you know in advance how many times the loop should run. It includes initialization, condition, and increment/decrement in one line.
Example
C++
C++
#include <iostream> using namespace std;
int main() {
for (int i = 0; i < 10; i++) {
cout << i << " ";
}
return 0;
}
You can also try this code with Online C++ Compiler
In C++, the concepts of true & false are fundamental to control structures. They are used to evaluate conditions & determine the flow of the program. In C++, any non-zero value is considered true, while zero is considered false.
Example
C++
C++
#include <iostream> using namespace std; int a = 5;
if (a) {
cout << "a is true" << endl;
} else {
cout << "a is false" << endl;
}
int b = 0;
if (b) {
cout << "b is true" << endl;
} else {
cout << "b is false" << endl;
} return 0; }
You can also try this code with Online C++ Compiler
In this example, since a has a non-zero value (5), it is considered true, & the code inside the if block is executed. On the other hand, b has a value of zero, so it is considered false, & the code inside the else block is executed.
C++ also provides the bool data type, which can hold only two possible values: true or false. You can use boolean variables to store the result of a condition.
Example
C++
C++
#include <iostream> using namespace std; bool isRaining = true;
if (isRaining) {
cout << "Remember to bring an umbrella!" << endl;
} else {
cout << "Enjoy the sunny day!" << endl;
} return 0; }
You can also try this code with Online C++ Compiler
In this example, the boolean variable isRaining is set to true. Since the condition isRaining is true, the code inside the if block is executed.
Logical Operators
Logical operators in C++ are used to combine or modify boolean expressions. They allow you to create more complex conditions by evaluating multiple expressions. The three main logical operators in C++ are:
Logical AND (&&)
The logical AND operator returns true only if both operands are true. It has the following truth table:
Example:
C++
C++
#include <iostream> using namespace std; int age = 25;
bool hasLicense = true;
if (age >= 18 && hasLicense) {
cout << "You are allowed to drive." << endl;
} else {
cout << "You are not allowed to drive." << endl;
} return 0; }
You can also try this code with Online C++ Compiler
In this example, the condition score >= 90 || score >= 80 is true if either score is greater than or equal to 90 or score is greater than or equal to 80.
Logical NOT (!)
The logical NOT operator, also known as the negation operator, returns the opposite of the operand's boolean value. It has the following truth table:
Example
C++
C++
#include <iostream> using namespace std; int main() { bool isRaining = false;
if (!isRaining) {
cout << "It's not raining. You can go outside." << endl;
} else {
cout << "It's raining. Stay inside." << endl;
}
return 0; }
You can also try this code with Online C++ Compiler
In this example, the condition !isRaining is true when isRaining is false.
Note : Logical operators are essential for creating complex conditions & controlling the flow of your program based on multiple factors.
Conditional Operator
The conditional operator, also known as the ternary operator, is a shorthand way of writing an if-else statement. It allows you to assign a value to a variable based on a condition. The syntax of the conditional operator is as follows:
(condition) ? expression1 : expression2
If the condition is true, expression1 is evaluated & its value is returned. If the condition is false, expression2 is evaluated & its value is returned.
Example
C++
C++
#include <iostream> using namespace std; int main() { int age = 20;
string status = (age >= 18) ? "Adult" : "Minor";
cout << "Your status is: " << status << endl;
return 0; }
You can also try this code with Online C++ Compiler
In this example, the condition age >= 18 is evaluated. Since age is 20, which is greater than or equal to 18, the condition is true. Therefore, the value "Adult" is assigned to the status variable.
Here's another example that shows the use of the conditional operator to find the maximum of two numbers:
C++
C++
#include <iostream> using namespace std; int main() { int a = 10; int b = 20; int max = (a > b) ? a : b;
cout << "The maximum number is: " << max << std::endl;
return 0; }
You can also try this code with Online C++ Compiler
In this example, the condition a > b is evaluated. Since a is less than b, the condition is false. Therefore, the value of b, which is 20, is assigned to the max variable.
The conditional operator provides a concise way to write simple if-else statements. It can be particularly useful when you need to assign a value based on a condition without writing a full if-else block.
Frequently Asked Questions
What is the purpose of switch statements in C++?
Switch statements provide a way to execute one out of several code blocks based on the value of a variable. They are cleaner and more efficient for multiple condition checks compared to multiple if-else statements.
Can while and do-while loops be used interchangeably?
While both are used for repeating actions, while checks the condition at the beginning, and do-while checks it at the end. This means do-while will always execute at least once, making them not completely interchangeable.
How does the conditional operator differ from an if-else statement?
The conditional operator is a compact form for assigning one of two values based on a condition. Unlike if-else, it cannot execute complex statements but is ideal for simple conditional assignments.
Conclusion
In this article, we have learned about control structures in C++, which are essential for controlling the flow of a program. We discussed the different types of control structures, which includes sequential, selection, & iteration. We also saw the various control statements in C++, such as if, if-else, switch, & loops. Moreover, we explained the concepts of true & false, logical operators, & the conditional operator.