Control(Selection) statements in c++
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 with zero is not allowed. This means that before writing the formula written above, it must first check 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 write a message that division with 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: 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.
Example: 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 : 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
"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 : Enter the whole number and determine its sign, ie whether the number is positive, zero or negative
cin>>a;
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 : 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;
Example 3: 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
Previous
|< Operators in C++ |
Next
Loops in C/C++ >| |