Almost all the programs you have seen so far have been linear. But what if you want to have a choice? That's where the conditional statement comes into play.
The conditional statement is a construction that allows a program to perform different computations depending on the value of a Boolean expression. If it is true, the program performs one computation; otherwise, if it is false, the program performs another computation. Here are some examples of Boolean expressions: a > b, i - j == 1, and so on.
Many computational systems, including those at the lowest level, operate on the principle of representing truth values using binary logic, where true is typically a positive value (often 1), and false is a non-positive value (usually 0). In C++ and many programming languages, true is conventionally represented by the integer value 1, while false is represented by the integer value 0.
The single if statement
The simplest form of the conditional statement consists of the keyword if. Here is a block diagram of how such a condition works:
If the condition inside the if block is true (equal to true or 1), then some code is executed; otherwise, the program simply continues its execution. In the source code, it appears like this:
#include <iostream>
int main(){
if(true){
std::cout << "Useless check, this text will always be displayed" << std::endl;
}
bool isDark = 1; //you can use true(1) or false(0)
if(isDark){
std::cout << "Yep, it's dark now!" << std::endl;
}
isDark = false;
if(isDark){
std::cout << "Nope, it's not dark now (light)!" << std::endl;
std::cout << "But this text is NEVER printed!!" << std::endl;
}
return 0;
}
false) in conditional expressions, such as the if statement or loops will be considered true, while a zero value will be considered false.
This is very convenient to use in practice. For example, if the user inputs numbers that you need to divide, you don't have to write something like:
if(divider == 0){
//some code
}
You just need to write:
if(divider){
//some code
}
It may seem like a minor detail, but understanding this principle simplifies development and expands the boundaries of code comprehension. You can use a conditional statement in any place in a program where the statement is expected. You can even nest it inside another conditional statement to perform multistage checks.
The if-else
You can extend the if case above with the keyword else and another body to do alternative actions when the expression is false.
In this case, if the expression is true, then the first code block is executed; otherwise, the second code block is executed, but not both together. In the source code, it looks like this:
#include <iostream>
int main(){
int numerator, denominator;
std::cin >> numerator >> denominator;
if(denominator){
std::cout << "The result is: ";
std::cout << numerator/denominator << std::endl;
}
else{
std::cout << "Unfortunately the divisor is 0" << std::endl;
}
return 0;
}
Here are some examples of how the program works (feel free to copy the code and test it on your computer):
Let's divide the numbers, enter two numbers:
4
2
The result is: 2
Try to divide by 0 yourself (the main thing is that we handle such a case, and our compiler does not swear).
But you don't have to stop there, you can combine any number of if else through the else if construct:
#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if(number == 1) {
std::cout << "Number is 1" << std::endl;
} else if(number == 2) {
std::cout << "Number is 2" << std::endl;
} else if(number == 3) {
std::cout << "Number is 3" << std::endl;
} else if(number == 4) {
std::cout << "Number is 4" << std::endl;
} else {
std::cout << "Number is not 1, 2, 3, or 4" << std::endl;
}
return 0;
}
Here is an example of this code execution:
Enter a number: 89
Number is not 1, 2, 3, or 4Ternary operator
Very often, during program development, you need to perform something similar to the following:
if (a > b) {
max = a;
} else {
max = b;
}
There are a lot of parentheses and unnecessary code (especially if you have 50 or more of such occurrences). It is possible to simplify it a bit (C++ allows you to do so):
if (a > b)
max = a;
else
max = b;
if or else will be processed!
Or you may do it conveniently with the help of the ternary operator.
The ternary operator is an operator which evaluates a condition and chooses one of two cases to execute. It can be considered a form of the if-then-else statement. Sometimes the ternary operator is more readable and concise than the corresponding if statement.
Here is what an equivalent ternary operator looks like:
max = a > b ? a : b;
This code is more concise than the code above, isn't it? The general syntax of the ternary operator is the following:
result = condition ? trueCase : elseCase;
It includes two special symbols ? and :.
Here, the condition is a boolean expression that evaluates to either true or false. If this expression is true, the ternary operator evaluates trueCase, otherwise elseCase is evaluated. It is important that trueCase and elseCase are expressions that can be reduced to a common type. This type determines the type of the result.
Here are two complete examples of using the ternary operator:
#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
std::string result = (number % 2 == 0) ? "even" : "odd";
std::cout << "The number is " << result << std::endl;
return 0;
}
Here's a slightly more complicated example:
#include <iostream>
int main() {
int a, b;
std::cout << "Enter a numbers: ";
std::cin >> a >> b;
std::string result = a == b ? "equal" :
a > b ? "more" : "less";
std::cout << result << std::endl;
return 0;
}
At first, the outer ternary operator checks the equality of a and b numbers. If it is true, equal is printed, otherwise, the nested ternary operator a > b ? "more" : "less" is calculated. To improve readability, the whole expression is divided into two lines.
Conclusion
The if/else conditional statement is a fundamental construct in C++ that allows for decision-making and controlling the flow of execution based on certain conditions. The if-else statement enables branching in the program's logic, providing alternate paths for different outcomes.
Additionally, we discussed the ternary operator as a concise way to express simple conditional expressions in a single line. It offers a shorthand alternative to the if-else statement and can be used when assigning values based on a condition.