Understanding Conditional Logic
with Nested Conditions



What are Nested Conditions?

Nested conditions are conditional statements placed inside other conditional statements. They are used when a decision depends on the outcome of a previous decision. This allows for more complex, multi-level decision-making in your programs.

Why Use Nested Conditions?

Sometimes, your logic needs to ask another question only if the first one passes. In such cases, you use one if block inside another if block — that’s called nesting.

Basic Structure

if (condition1) {
    // do something
    if (condition2) {
        // do something more
    } else {
        // another path
    }
} else {
    // fallback path
}

Example 1: Age and Citizenship Check

Imagine a voting eligibility check. To vote, a person must be at least 18 years old and a citizen.

if (age >= 18) {
    if (citizenship == "yes") {
        print("You are eligible to vote")
    } else {
        print("You must be a citizen to vote")
    }
} else {
    print("You must be at least 18 years old to vote")
}

Output:

You are eligible to vote

Explanation:

Question:

What happens if age is less than 18?

Answer: The inner condition (citizenship check) is never reached. The outer condition fails and directly prints the age-related message.

Example 2: Multi-level Access Check

Suppose we are granting access to a system based on login and role:

if (isLoggedIn == true) {
    if (role == "admin") {
        print("Access granted: Admin dashboard")
    } else if (role == "user") {
        print("Access granted: User dashboard")
    } else {
        print("Access granted: Guest view")
    }
} else {
    print("Please log in to continue")
}

Output:

Access granted: User dashboard

Explanation:

Question:

Can we avoid nesting here?

Answer: In some cases, yes. You could use a flat structure with combined conditions. But nesting improves clarity when one check logically depends on another.

Best Practices

Recap



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M