0
0
C++programming~5 mins

Nested conditional statements in C++

Choose your learning style9 modes available
Introduction

Nested conditional statements help you make decisions inside other decisions. This lets your program check many things step by step.

When you want to check if a number is positive, and then check if it is even or odd.
When you need to decide a grade based on score ranges, then check if the student passed or failed.
When you want to check if a user is logged in, and then check their role to show different options.
When you want to check the weather condition, and then decide what clothes to wear based on temperature.
Syntax
C++
if (condition1) {
    if (condition2) {
        // code if both condition1 and condition2 are true
    } else {
        // code if condition1 is true but condition2 is false
    }
} else {
    // code if condition1 is false
}

You can put one if statement inside another to check multiple things.

Use curly braces { } to group the code inside each condition clearly.

Examples
Check if x is positive, then inside that check if x is even.
C++
if (x > 0) {
    if (x % 2 == 0) {
        // x is positive and even
    }
}
First check if score is passing, then check for higher grades inside.
C++
if (score >= 50) {
    if (score >= 90) {
        // grade A
    } else {
        // grade B or C
    }
} else {
    // failed
}
Sample Program

This program asks the user for a number. It first checks if the number is positive. If yes, it then checks if it is even or odd and prints the result. If not positive, it says so.

C++
#include <iostream>
using namespace std;

int main() {
    int number;
    cout << "Enter an integer: ";
    cin >> number;

    if (number > 0) {
        if (number % 2 == 0) {
            cout << number << " is positive and even." << endl;
        } else {
            cout << number << " is positive and odd." << endl;
        }
    } else {
        cout << number << " is not positive." << endl;
    }

    return 0;
}
OutputSuccess
Important Notes

Indent your code inside each if or else block to keep it clear and easy to read.

Remember that nested conditions can get complex, so keep them simple and clear.

Summary

Nested conditionals let you check one condition inside another.

Use them to make decisions that depend on multiple checks.

Always use braces and indentation for clarity.