Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Types of Control Structure in C++
2.1.
Sequential Control Structure
2.2.
C++
2.3.
Selection Control Structure:
2.4.
C++
2.5.
Iteration Control Structure
2.6.
C++
3.
Control statements in C/C++ to Implement Control Structures
3.1.
if statement
3.2.
C++
3.3.
if-else statement
3.4.
C++
3.5.
switch statement
3.6.
C++
3.7.
for Loop
3.8.
C++
3.9.
while Loop
3.10.
C++
3.11.
do-while Loop
3.12.
C++
4.
True and False
4.1.
Example
4.2.
C++
4.3.
Example
4.4.
C++
5.
Logical Operators
5.1.
Logical AND (&&)
5.2.
C++
5.3.
Logical OR (||)
5.4.
C++
5.5.
Logical NOT (!)
5.6.
C++
6.
Conditional Operator
6.1.
Example
6.2.
C++
6.3.
C++
7.
Frequently Asked Questions
7.1.
What is the purpose of switch statements in C++?
7.2.
Can while and do-while loops be used interchangeably?
7.3.
How does the conditional operator differ from an if-else statement?
8.
Conclusion
Last Updated: Jun 11, 2024
Easy

Control Structures in C++

Author Rinki Deka
0 upvote

Introduction

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. 

Control Structures in C++

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
Run Code

Output:

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
Run Code

 

Output

Positive number

Iteration Control Structure

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
Run Code

Output: 

1 2 3 4 5

Control statements in C/C++ to Implement Control Structures

C++ provides various control statements that allow you to implement the different control structures mentioned earlier. Let's discuss each of them.

if statement

The if statement is used to execute a block of code only if a specified condition is true. It has the following syntax:

if (condition) {
    // code to be executed if the condition is true
}

Here's an example:

  • C++

C++

#include <iostream>
using namespace std;
int main() {

int age = 18;

if (age >= 18) {

   cout << "You are eligible to vote." << endl;

}

return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

You are eligible to vote.


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
Run Code

Output

The number is odd.


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
Run Code

Output

Wednesday


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
Run Code

Output: 

0 1 2 3 4 5 6 7 8 9

while Loop

Used when the number of iterations is not known before the loop starts. It checks the condition before executing the loop body.

Example

  • C++

C++

#include <iostream>
using namespace std;

int main (){

int i = 0;

while (i < 5) {

   cout << i << " ";

   i++;

}

return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output: 

0 1 2 3 4

do-while Loop

Similar to the while loop, but it checks the condition after executing the loop body, ensuring the loop executes at least once.

Example 

  • C++

C++

#include <iostream>
using namespace std;

int main(){

int j = 0;

do {

   cout << j << " ";

   j++;

} while (j < 5);

return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output: 

0 1 2 3 4

True and False

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
Run Code

Output:

a is true
b is false


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
Run Code

Output:

Remember to bring an umbrella!


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:

Logical AND (&&)

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
Run Code

Output

You are allowed to drive

In this example, the condition age >= 18 && hasLicense is true only if both age is greater than or equal to 18 and hasLicense is true.

Logical OR (||)

The logical OR operator returns true if at least one of the operands is true. It has the following truth table:

Logical OR (||)

Example:

  • C++

C++

#include <iostream>
using namespace std;
int main() {

int score = 80;

if (score >= 90 || score >= 80) {

cout << "You passed the exam!" << endl;

} else {

cout << "You failed the exam." << endl;

}
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

You passed the exam!


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:

Logical NOT (!)

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
Run Code

Output

It's not raining. You can go outside.


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
Run Code


Output:

Your status is: Adult


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
Run Code

Output

The maximum number is: 20

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. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass