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 first ask the user for their gender. The input is then read and processed through an if-else block, where our βhelloβ is provided for the female gender and the output βbyeβ is provided if the input is male gender.
In the 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.
We have three types of loops in C++:
- While loop
- Do-while loop
We will explore all of them in more detail later on.
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, checks whether i is less than 10, and continues the process until the value of i reaches 10.
Quick Recap
- Sequence: Executes statements in the exact order they appear, no conditions, no jumps.
- Selection: Makes decisions using if, if-else, else-if, and switch based on conditions.
- Iteration: Repeats a block of code using for, while, and do-while loops.
- Jumping: Alters normal flow using break, continue, goto, and exit() for special control needs.
Control Statements in C++ to Implement Control Structures
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
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.
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;
}
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. If not, the else block's function 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;
}
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 to check 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;
}
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
| If-else statement |
Switch statement |
Feature |
| Used for evaluating multiple conditions involving relational, logical, or equality operators. |
Used when multiple values of a single variable need to be compared. |
Usage |
| 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. |
Flow |
| Can be slower when there are many conditions since it checks conditions one by one. |
Generally faster when handling multiple constant values. |
Efficiency |
| Can become difficult to read when there are too many conditions. |
Easier to read and manage when dealing with multiple fixed values. |
Readability |
| The else block executes when no conditions are met. |
The default case executes when no matching case values are found. |
Default Case |
Summary
- if / if-else: Runs code when conditions are met, enabling decision-making.
- if-else-if ladder: Handles multiple possible outcomes in a clean, ordered way.
- switch: Efficiently selects one block from many constant-value options.
- Loops (for / while / do-while): Repeatedly execute code until a condition changes.
- Jump statements: Break out, skip iterations, or reroute execution based on program needs.
Iteration 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 f = 1; f <= 5; f++) {
cout << f << " ";
}
return 0;
}
Output
1 2 3 4 5
Explanation
- Initialization: int f = 1; The loop starts with f = 1.
- Condition: f \<= 5; Runs as long as i is less than or equal to 5.
- Increment: f++; Increases f by 1 in each iteration.
- Prints Numbers: cout \<\< f \<\< " "; 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 e = 1; // Initialization
// While loop to print numbers from 1 to 5
while (e <= 5) {
cout << e << " ";
e++; // Increment
}
return 0;
}
Output
1 2 3 4 5
Explanation
- Initialization: int e = 1; The loop starts with e = 1.
- Condition: while (e \<= 5); Runs as long as e is less than or equal to 5.
- Execution: cout \<\< e \<\< " "; prints e in each iteration.
- Increment: e++; increases e by 1 in every iteration.
3. Do-while loop
Similar to a while loop, the do-while loop operates as well. The only distinction is that each time the loop is executed, the condition is checked. This ensures that, even if the condition is never met, the function inside the loop executes at least once.
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.
- For i == 3, the continue statement passes the remainder of the loop body and advances to the subsequent 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.
Recap
- for loop: Mostly used when the number of repetitions is determined; the initialization, condition, and update are generally kept in one line.
- while loop: It keeps running until the condition is true; it is used when the number of iterations is not known.
- do-while loop: The condition is checked only after the body has been executed at least one ββββββββββββββββtime.Β
Together, these loops automate repetitive tasks and improve code efficiency.
Boolean Data Type in C++
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 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.
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;
}
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
Note
- C++ uses bool to represent true or false, forming the backbone of all condition checks.
- Any non-zero value evaluates to true, while 0 evaluates to false.
- Control structures rely heavily on boolean evaluation to decide what executes next.
Logical and Conditional Operators in C++
Logical 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.
Logical Operators
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
| Condition 1 |
Condition 2 |
Result |
| true |
true |
true |
| true |
false |
false |
| false |
true |
false |
| false |
false |
false |
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;
}
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
| Condition 1 |
Condition 2 |
Result |
| true |
true |
true |
| true |
false |
true |
| false |
true |
true |
| false |
false |
false |
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;
}
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
| condition |
result |
| true |
false |
| false |
true |
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;
}
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."
Key Takeaways
- C++ββββββββββββββββ uses try, catch, and throw to handle runtime errors, which is a method that stops errors from causing the program to crash and allows the program to recover in a safe way.Β
- Use exceptions to detect issues like division by zero, invalid array access, or file failures.
- Structured error handling makes programs more stable, predictable, and less time-consuming in terms of debugging.
Conditional (Ternary) Operator
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.
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;
}
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.
Output
Enter a number: 8
The number is Even.
Enter a number: 5
The number is Odd.
When to Use:
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.
Combining Logical and Conditional Operators
It is possible to combine logical operators inside the conditional (ternary) operator in order to have a compact, expressive decision logic.
Example:
string result = (num > 0 && num % 2 == 0)
? "Positive and even"
: "Not positive and even";
Summary
Logical operators (& &, ||, !) give you 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.
Error Handling Structures
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;
}
Conclusion
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.
Points to Remember While Learning Control Structures
- Start with the logic, not the syntax, and know why a control structure is needed.
- Execution should use sequence if it is simple and straightforward, selection if it is a decision, and iteration if it is repetition.Β
- It is better to have simple and readable conditions in order not to make logical mistakes.Β
- Choose a switch when comparing a single variable against multiple fixed values.
- Prefer loops over goto for clarity and maintainability.
- Be aware that Boolean expressions are at the core of all decisions in C++.Β
- Always remember that if you are testing edge cases in loops, you should do so in order to avoid infinite iterations.Β
- In case of unexpected runtime issues, error handling (tryβcatch) should be used to resolve them ββββββββββββββββsafely.
Frequently Asked Questions
1. What is a control structure in C++?
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.
2. Explain control structures in C++.
Control structures in C++ are categorized into three main types:
- Sequential Control Structure: This simply executes the statements one after another in the order that they appear.
- Selection Control Structure: The selection control structure implements conditions (if, else if, else, switch) to decide which code block will be executed depending on the condition satisfied.
- Iteration Control Structure: The iteration control structure makes use of loops (for, while, do-while) to repeat pieces of code until a certain condition is true.
3. Difference between while and do-while loops in C++?
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.
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 use 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++?
To break out of a loop before it ends, use the break statement.
7. What is the main role of the continue statement in loop control?
The continue statement moves on to the next iteration of a loop by omitting the remaining code in the current iteration.