C++ Code Example: nested if-else statement

When an if-else statement is executed in the body of another if-else statement, it is called nested.

Code Explanation

LineDescription
5Initializes the variable number with the value 61
7If the value of number is less than or equal to 100
8 – 9If the value of number is less than 50, print the string “Value is smaller than 50”
10 – 11If the value of number is less than 50, print the string “Value is 50”
12 – 13Otherwise the string Value is between 51 und 100 is output
15 – 16If the value of number is greater than 100 the following string “Value is greater than 100” is output
19The main function expects a return value of type int -> int main(). Therefore the value 0 is returned
#include <iostream>
using namespace std;

int main() {
    int number = 61;
    
    if (number <= 100) {
        if (number < 50) {
            cout << "Value is smaller than 50";
        } else if (number == 50) {
            cout << "Value is 50";
        } else {
            cout << "Value is between 51 und  100";
        }
    } else {
        cout << "Value is greater than 100";
    }

    return 0;
}
Output
Value is between 51 und 100