If else Statement in C++

Sometimes we need to execute a block of statements only when a particular condition is met or not met. This is called decision making, as we are executing a certain code after making a decision in the program logic. For decision making in C++, we have four types of control statements (or control structures), which are as follows:

If statement in C++

If statement consists a condition, followed by statement or a set of statements as shown below:

if(condition){
Statement(s);
}

The statements inside if parenthesis (usually referred as if body) gets executed only when the given condition is true. If the condition is false then the statements inside if body are completely ignored.

If else statement in C++

Sometimes you have a condition and you want to execute a block of code if condition is true and execute another piece of code if the same condition is false. This can be achieved in C++ using if-else statement.

This is how an if-else statement looks:

if(condition) {
Statement(s);
}
else {
Statement(s);
}

The statements inside “if” would execute if the condition is true, and the statements inside “else” would execute if the condition is false.

Flow diagram of if-else

Example of if-else statement

#include <iostream>
using namespace std;
int main(){
int num=66;
if( num < 50 ){
//This would run if above condition is true
cout<<"num is less than 50";
}
else {
//This would run if above condition is false
cout<<"num is greater than or equal 50";
}
return 0;
}

Output:

num is greater than or equal 50

if-else-if Statement in C++

if-else-if statement is used when we need to check multiple conditions. In this control structure we have only one “if” and one “else”, however we can have multiple “else if” blocks. This is how it looks:

Note: The most important point to note here is that in if-else-if, as soon as the condition is met, the corresponding set of statements get executed, rest gets ignored. If none of the condition is met then the statements inside “else” gets executed.