Control(Selection) statements in c++
Lesson Content: Selection Statements in C++
Welcome to the lesson dedicated to selection statements in C++! In this lesson, we will explain in detail how conditional branching works using if-else and switch statements. You will learn the basic concepts of conditional branching, how to use if, if-else, and switch statements, and understand their advantages and common pitfalls.
Introduction
In simple examples in the C++ programming language, commands were executed in one flow, i.e., one after the other, until the very end of the program. Sometimes in the program, some commands are executed under a certain condition.
For example, consider the following problem: For the entered numbers a and b, calculate the value of the fraction a / b.
After the declaration of variables and entries a and b by the user, we come to the part where it is necessary to calculate the fraction. Is it possible to simply introduce the variable c and calculate c = a / b?
It is known that division by zero is not allowed. This means that before writing the formula mentioned above, it must first be checked whether the condition that b is different from zero is met. If so, then you can write a formula and print the result. Otherwise, something alternative can be done, e.g., to display a message that division by zero is not allowed, or to do nothing.
We conclude that there are two variants of program execution, or only one, which depends on the condition of whether b is different from zero or not. This means that branching occurs in the program and that branching is done on the basis of logical data or expressions.
Branching in a program with 2 branches
However, there are situations when it is necessary to enable the execution of a certain command only if a certain condition is met, while in the second flow there are no commands to execute. This is called conditional execution, and the flow chart for such situations is shown in the following figure (Figure 2).
In the left flowchart, if the value of the condition is 0 (FALSE), the program skips statement 2 and continues without executing it. In the right flowchart, we see similar branching with the addition of the ability to skip execution in one branch if a condition is not met.
In C++, this kind of branching often uses keywords like if and else, and due to the existence of the bool data type, the expressions used for the condition can be more expressive and intuitive. For example:
statement2();
// The flow continues here without an additional branch
Similarities and differences with branching in the C language
Simililarities:
- Both languages use if, else if, else, and switch to control program flow.
- The syntax for these structures is identical:
Both languages use the same logical operators:
- && (logical "and"),
- || (logical "or"),
- ! (logical negation).
- Both languages use break to break switch branching and default for default cases.
Differences
1. Data types in conditions
C:
In C, a condition in branching can be any expression that can be interpreted as an integer value:
- 0 is considered false.
- Anything other than 0 is considered true.
Example:
C++:
C++ has stricter logic and supports the bool
type introduced in C++98.
In C++, it is recommended to use bool
for logical conditions, making the code more readable and less error-prone.
Example:
if (condition) {
2. Functionality in branching
C:
Does not support advanced mechanisms like lambda expressions or traditional std::function
objects for logical expressions.
C++:
Provides additional features such as lambda expressions, enabling more complex and flexible branching:
if (condition()) {
3. Switch with complex expressions
C:
switch
in C can only use integral types (int
, char
, enum
).
C++:
In modern versions of C++ (C++11 and later), constexpr
expressions and enum class
can be used in switch
structures, which is not possible in C.
4. Else if vs else if as a single block
C:
Technically, else if
is not a specific keyword but rather a combination of else
{ if
}.
C++:
The functionality remains the same, but due to stricter type logic, logical expressions in branching can be checked using compiler static analysis.
5. Integration with Object-Oriented Concepts (C++)
In C++, branching can integrate with class methods and properties, enabling more complex logic in object-oriented programs.
Conclusion
While basic branching structures in C and C++ remain similar, C++ provides additional functionality that allows for greater flexibility and better integration with modern programming practices, such as the use of bool
type, lambda expressions, and constexpr
evaluation. In C, the focus remains on simplicity and compatibility with older versions of the language.
Logical data
true
false
For the type of this data, the official word of the C ++ bool language is used
Logical data and expressions
<, >, <=, >=, !, !=, ==
"Less than", "greater than", "less than or equal", "greater or equal", "negation", "not equal", "equally"
Example of logical expressions in C ++
bool b;
c=a+b; //integer expression
c=a>b; //false
b=a>b; //b=true
b=!(a>b); //b=false
Logical data and more complex expressions
Logical Data
These are data whose value is the result of a logical expression and can have two states:
- true - true
- false - false
The official C++ keyword for this type of data is bool.
Logical Data and Expressions
Logical relations, i.e., expressions, are expressions that are results of comparisons and use the following operators:
“less than,” “greater than,” “less than or equal to,” “greater than or equal to,” “negation,” “not equal to,” “equal to”
Example of Logical Expressions in C++
bool d;
c = a + b; // integer expression
c = a > b; // invalid, mismatched data types
d = a > b; // valid, results in true
d = !(a > b); // false
Logical Data and Complex Expressions
To combine multiple smaller logical expressions, we use the operators:
- && – Logical “and”
- || – Logical “or”
Assume we have the following code:
a = 10, b = 4, c = 2;
bool d, e;
d = (a == 0) && (b > c); /* d = false && true;
d = false; */
e = (a == 0) || (b > c); /* e = false || true;
e = true; */
Complex Logical Expressions with “&&”
A complex logical expression obtained by combining two simple logical expressions with && will be true only if both simple expressions are true, i.e.:
true && false = false
false && true = false
false && false = false
Complex Logical Expressions with “||”
A complex logical expression obtained by combining two simple logical expressions with || will be true if at least one of the simple expressions is true, i.e.:
true || false = true
false || true = true
false || false = false
Programming and logical data
A condition on the diagram can be either a logical data of type bool or a logical expression, also of type bool.
In the picture on the right, branching into two branches is shown, based on the logical variable Condition (or logical expression). If it is correct, the branch to the left will be executed, i.e. command 2, and if false then command 3 will be executed.
This is made possible by an if statement (for the case on the left) or an if-else statement for the case on the right.
Branching in a program: the if-else statement
if(condition)
{
else
{
Selections - command if
if(condition)
{
Example 1: Checking the correctness of the entered data
Task
Enter the length of the square's side a and check if the data is valid.
Note: The data is considered valid if it is a positive number.
Solution in C++
// Validate the input length of the square's side
using namespace std;
int main() {
cout << "Enter the length of the square's side: ";
cin >> a;
if (a > 0) {
return 0;
Explanation
- #include <iostream> includes the library for input and output operations.
- cin is used to input the value of the variable a, representing the square's side length.
- The program checks whether a is greater than zero:
- If true, it prints a message stating that the length is valid.
- If false, it warns that the length must be a positive number.
- Finally, the program returns 0, indicating successful execution.
Test your code in the editor!
Example 2: Enter an integer and determine if it is divisible by 3
A number is divisible by 3 if the remainder of dividing the entered number by 3 is zero. We will use the if-else statement to create branching in the program, so that in one branch the message (cout) "The number is divisible by 3" will be printed, while in the other branch another message will be printed: "The number is not divisible by 3".
In order to write the condition for branching, it is necessary to determine the remainder of the division. The "%" operator is used for this.
Therefore, the remainder of the division of the number a and the number 3 is: a%3.
It is then checked to see if it is equal to zero. So,
a%3 == 0
/* Enter an integer and determine if it is divisible by 3 */
int main()
{
std::cout << "Enter an integer: " << std::endl;
std::cin >> a;
if ((a % 3) == 0)
Example 3: Enter two real numbers x and y, and calculate the value of the fraction
// Declare three variables: 'a', 'b' (real numbers) and 'fraction' (to store the result of division)
std::cout << "Enter two real numbers a and b!" << std::endl;
// Prompt the user to enter two real numbers
std::cin >> a >> b;
// Read the values of 'a' and 'b' from the user
fraction = a / b;
// Calculate the fraction by dividing 'a' by 'b'
std::cout << fraction;
// Output the result of the division
To ensure that there is no division if b is equal to zero, we will use the if command
cout << "Enter two real numbers a and b!" << endl; cin >> a >> b;
if(b != 0)
{
fraction=a/b;
}
cout << fraction;
// Declare three variables: 'a', 'b' (real numbers) and 'fraction' (to store the result of division)
std::cout << "Enter two real numbers a and b!" << std::endl;
// Prompt the user to enter two real numbers
std::cin >> a >> b;
// Read the values of 'a' and 'b' from the user
if(b != 0)
{
// Calculate the fraction by dividing 'a' by 'b' if 'b' is not zero
else
{
// Display an error message if 'b' is zero
std::cout << fraction;
// Output the result of the division (or a default value if no division occurred)
A more detailed explanation of the "if" statement
The "if" statement allows conditional execution of code based on a specific condition.
Syntax:
// Code to execute if the condition is true
}
Example with a simple condition:
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (number > 0) {
cout << "The number is positive." << endl;
}
return 0;
}
In this example, the code inside the if
block is executed only if the condition number > 0
is true.
Complex Conditions
Often, multiple conditions need to be evaluated. Logical operators such as &&
(AND) and ||
(OR) are used for combining conditions:
Example with logical operators:
using namespace std;
int main() {
int x, y;
cout << "Enter two values (x and y): ";
cin >> x >> y;
if (x > 0 && y < 10) {
cout << "x is positive and y is less than 10." << endl;
}
if (x < 0 || y > 20) {
cout << "x is negative or y is greater than 20." << endl;
}
return 0;
}
Explanation:
x > 0 && y < 10
: Both conditions must be true for the code inside theif
block to execute.x < 0 || y > 20
: The code executes if at least one condition is true.
Nested "if" Statements
When conditions are dependent, nested if
statements can be used:
Example with nested "if":
using namespace std;
int main() {
int grade;
cout << "Enter a grade (1-5): ";
cin >> grade;
if (grade >= 1 && grade <= 5) {
if (grade == 5) {
cout << "Excellent!" << endl;
} else if (grade == 4) {
cout << "Very good." << endl;
} else if (grade == 3) {
cout << "Good." << endl;
} else if (grade == 2) {
cout << "Sufficient." << endl;
} else {
cout << "Insufficient." << endl;
}
} else {
cout << "Invalid grade!" << endl;
}
return 0;
}
Explanation:
- The outer
if
ensures the grade is valid. - The inner
if-else
block handles specific cases for grades.
Branching in a 3-branch program
if(Condition1)
{
else if(Condition2)
{
else
{
Explanation:
- Structure of the code:
The code shows the structure of the if-else if-else statement in C++ language, which allows branching the program flow based on different conditions.
- Code elements:
Condition1, Condition2 are logical expressions (conditions).
- If Condition1 is true, statements 1 will be executed, and the other branches will be skipped.
- If Condition1 is false, but Condition2 is true, statements 2 will be executed, and the other branches will be skipped.
- If both Condition1 and Condition2 are false, statements 3 from the else block will be executed.
- Behavior description:
if (Condition1):
Checks the first condition (Condition1). If it is true, it executes the code inside the first branch (statements 1), and the other branches are ignored.else if (Condition2):
Checks the second condition (Condition2) only if the first condition is false. If the second condition is true, it executes the code inside the second branch (statements 2).else:
Executes only if all the previous conditions are false. This block provides the "default" scenario (statements 3).
- Role of colors:
Statements 1, 2, and 3 use different colors to highlight their function:
- Green: Statements that execute for the first branch (if).
- Red: Statements that execute for the second branch (else if).
- Blue: Statements that execute in the final branch (else).
- Example use:
Imagine a program that analyzes a student's grade and gives feedback:
The code represented by this diagram would be:
Branching in a program with more than 2 branches-video(with an English title)
Example 4: Enter the whole number and determine its sign, ie whether the number is positive, zero or negative
cin>>a;
if(a > 0) { cout << "The number is positive"; } else if(a == 0) { cout << "The number is zero"; } else { cout << "The number is negative"; }
If the first condition is incorrect, the program goes to another condition a == 0 next to else if.
If he is typing, the message "Number is equal to zero" and the rest of the expanded if the command is skipped.
If this condition is not true, then the command under another clause is executed. Note that besides else there are no conditions. It is not needed, because the command below is executed if all the previous conditions are incorrect. In this example, if the number was not positive and was not zero, it is assumed to be negative.
The clause else, if there is, is always the last. On the last, third place, instead of else, the command could end with else if. The difference over the other is that, besides else if it is necessary to write a certain requirement. In this example, the condition would be "a <0".
The next code would perform the set task in exactly the same way as it was performed using another clause in the last place:
cout << "The number is positive";
} else if(a == 0){
cout << "The number is zero";
}
else if(a <0 ){
cout << "The number is negative";
}
Example 5: Input two real numbers via standard input and compare their values
After entering the numbers
a
and b
from the keyboard, the program branches into 3 possible paths, since there are 3 possible outcomes. These outcomes are actually messages that will be printed using the cout
command:- "a is greater than b"
- "a is equal to b"
- "a is less than b"
First, we need to set the first condition using the
if
statement, for example, whether a
is greater than b
(a > b
). With this condition, we get two possible branches: one for the true condition, in which case the first message is printed, and another for the false condition. Since there are two other possibilities, we need at least one more condition. For example, "is a
equal to zero?" (a == 0
). This goes with the else if
clause immediately below the first branch. The second outcome will be printed if this condition is true. The third outcome will be printed if this condition is false, and it is handled by the else
clause.The code below demonstrates this process:
using namespace std;
// Program that prints the relationship between two numbers a and b
int main() {
cout << "Enter number a: ";
cin >> a;
cout << "Enter number b: ";
cin >> b;
if (a > b) {
return 0;
Of the three possible outcomes, i.e., three possible messages, only one will be executed:
- For the first condition being true, the first message will be executed.
- For the first condition being false, but the second condition true, the second message will be executed.
- For both the first and second conditions being false, the third message will be executed.
It is also important to note that the
else
clause, which can only be the last one, does not require an explicit condition to be written; it is implied. This means: if a > b
is false and a == b
is false, we conclude that a < b
.This can also be solved using an
else if
statement at the last position, but it would require an explicit condition:
using namespace std;
// Program that displays the relationship between two numbers a and b
int main() {
cout << "Enter number a: ";
cin >> a;
cout << "Enter number b: ";
cin >> b;
if (a > b) {
return 0;
Branching in a Program Based on the Value of an Integer Variable – switch Statement
Program branching can be performed not only based on one or more conditions but also based on different values of an integer variable, as shown in Figure 8.
Before branching occurs, an integer variable must be entered, assigned, or computed earlier in the code. Based on its possible values, branching is performed. Each of these possible values leads to a different branch in which certain commands will be executed (see Figure 8). If the variable's value is different from the offered ones, the program will take the default branch and execute its commands, if defined.
The switch statement is used to branch the execution of a program based on the value of an integer variable. In the example below, a variable named data
is defined and loaded, then the switch statement evaluates its value. Three cases (e.g. value_1, value_2, value_3) are provided, along with a default branch that is executed if none of the specified values match.
#include <iostream>
using namespace std;
int main() {
int data; // Declare the variable data
cout << "Enter data: " << endl; // Prompt for input
cin >> data;
switch(data) {
case 1: // If data equals value_1
cout << "Value 1 selected" << endl;// commands 1
break;
case 2: // If data equals value_2
cout << "Value 2 selected" << endl;// commands 2
break;
case 3: // If data equals value_3
cout << "Value 3 selected" << endl;// commands 3
break;
default: // If data does not match any case
cout << "Default case: value not recognized" << endl;
break;
}
return 0;
}
Example 6: Determining the Month Based on the Month Number
In this example, we demonstrate how to use the switch statement to determine the month name from an input month number.
A variable named month
is defined and loaded with the user input. The switch statement then checks the value of month
and directs the flow to one of three specific cases – for example, case 1, 2, and 3 – each printing a corresponding month name (January, February, March).
If the input does not match any of the defined cases (i.e. if the number is less than 1 or greater than 12), the default branch is executed and an error message is displayed.
#include <iostream>
using namespace std;
int main() {
int month; // Declare the month variable
cout << "Enter the month number: " << endl; // Prompt for input
cin >> month;
switch(month) {
case 1: // If month equals 1
cout << "January" << endl;
break;
case 2: // If month equals 2
cout << "February" << endl;
break;
case 3: // If month equals 3
cout << "March" << endl;
break;
default: // For any other value (invalid month)
cout << "Invalid input: month must be between 1 and 12" << endl;
break;
}
return 0; // End of program
}
Example 7: Determining the Number of Days in a Month
This program calculates the number of days in a month based on the user's input. The program reads an integer for the month and an integer for the year, then uses a switch statement to assign the correct number of days for that month. For February, it checks if the year is a leap year using the condition:
year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)
If the month is not valid (i.e. not between 1 and 12), the default branch is executed and an error message is displayed. Otherwise, the program prints the number of days for the specified month.
#include <iostream>
using namespace std;
int main() {
int month, year;
int numOfDays;
cout << "Enter the month and year!" << endl; // Prompt for input
cin >> month >> year;
bool invalidInput = false;
switch(month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numOfDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numOfDays = 30;
break;
case 2:
if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
numOfDays = 29; // Leap year
} else {
numOfDays = 28;
}
break;
default:
invalidInput = true;
}
if (!invalidInput) {
cout << "Number of days is: " << numOfDays << endl;
} else {
cout << "Invalid Input" << endl;
}
return 0;
}
Example 8: Selecting figures
Enable first the user to choose one of three geometric shapes:
1-Square, 2-Circle, 3-Parallelogram,
and then enter the required input data for the selected figure and calculate its area
Advanced Examples
Advanced examples can greatly enrich the content for experienced programmers by demonstrating complex decision-making in code. By incorporating examples with multiple conditions, nested if-else structures, and combined logical expressions, you can solve real-world problems with intricate logic.
For instance, consider a scenario where you need to determine a student's grade based on several criteria such as test scores, attendance, and assignment performance. A nested if-else structure with combined logical conditions can elegantly handle multiple criteria and edge cases.
Below is an example code snippet that demonstrates advanced branching using nested if-else statements and combined logical expressions:
#include <iostream>
using namespace std;
int main() {
int score;
cout << "Enter your score: " << endl; // Prompt for the student's score
cin >> score;
if (score >= 90) {
if (score >= 95) {
cout << "Grade: A+" << endl; // Score 95 or above gives A+
} else {
cout << "Grade: A" << endl; // Score between 90 and 94 gives A
}
} else if (score >= 80 && score < 90) {
cout << "Grade: B" << endl;
} else if (score >= 70 && score < 80) {
cout << "Grade: C" << endl;
} else {
cout << "Grade: F" << endl;
}
return 0; // End of program
}
In this example, nested if-else statements and combined logical conditions are used to determine the grade based on the student's score. The inner if-else distinguishes between an A+ and an A grade when the score is 90 or above, while other conditions determine grades B, C, or F. This demonstrates how advanced branching structures can handle multiple criteria in a single decision-making process.
Previous
|< Operators in C++ |
Next
Loops in C/C++ >| |