A selection structure is implemented using if-else expressions. The decision control instruction is implemented in C++ using the if keyword, just like in any other programming language.
The if statement’s condition is always encased in a pair of parentheses. The set of statements that follow the if statement will be executed if the condition is met. Additionally, the statement will not be executed if the condition evaluates to false; instead, the programme will skip the enclosing portion of code.
Relational operators are used to define an expression in if statements. If the expression after the if evaluates to true, the statement contained in the if block will be carried out. However, if the if block is followed by an else block, a sequence of statements in the else block will be executed when the if block’s condition is false.
Syntax:
if ( condition ){
statements;}
else {
statements;}
Example:
#include <iostream>
using namespace std;
int main()
{
int age;
cout << "Enter a number: ";
cin >> age;
if (age >= 50)
{
cout << "Input number is greater than 50!" << endl;
}
else if (age == 50)
{
cout << "Input number is equal to 50!" << endl;
}
else
{
cout << "Input number is less than 50!" << endl;
}
}
Input:
Enter a number: 53
Output:
Input number is greater than 50!