Open In App

Nested If Else Statement in Programming

Last Updated : 10 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Nested If Else Statements are a fundamental concept in programming. They allow us to create more complex decision-making structures by placing one if else statement inside another. In this article, we will discuss the Nested if else statement.

What is Nested If Else Statement?

Nested if else statements allow for more complex decision-making within the program. You can nest if else statements with other if else statements, creating conditions at multiple levels.

Syntax of Nested If Else Statement:

if (condition1) {
// Code block for condition1 being true
if (condition2) {
// Code block for condition1 and condition2 both being true
} else {
// Code block for condition1 being true and condition2 being false
}
} else {
// Code block for condition1 being false
}

Nested If Else Statement in C:

Here are the implementation of Nested if else statement in C language:

C
#include <stdio.h>

int main() {
    // Declare and initialize the variable num
    int num = 10;

    // Outer if-else statement to check if num is greater than 0
    if (num > 0) {
        printf("Number is positive.\n");

        // Nested if-else statement to check if num is even or odd
        if (num % 2 == 0) {
            printf("Number is even.\n");
        } else {
            printf("Number is odd.\n");
        }

    } else {
        // Execute if num is not greater than 0
        printf("Number is non-positive.\n");
    }

    return 0;
}

Output
Number is positive.
Number is even.

Nested If Else Statement in C++:

Here are the implementation of Nested if else statement in C++ language:

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

int main() {
    // Declare and initialize the variable num
    int num = 10;

    // Outer if-else statement to check if num is greater than 0
    if (num > 0) {
        cout << "Number is positive." << endl;

        // Nested if-else statement to check if num is even or odd
        if (num % 2 == 0) {
            cout << "Number is even." << endl;
        } else {
            cout << "Number is odd." << endl;
        }

    } else {
        // Execute if num is not greater than 0
        cout << "Number is non-positive." << endl;
    }

    return 0;
}

Output
Number is positive.
Number is even.

Nested If Else Statement in Java:

Here are the implementation of Nested if else statement in java language:

Java
public class Main {
    public static void main(String[] args) {
        // Declare and initialize the variable num
        int num = 10;

        // Outer if-else statement to check if num is greater than 0
        if (num > 0) {
            System.out.println("Number is positive.");

            // Nested if-else statement to check if num is even or odd
            if (num % 2 == 0) {
                System.out.println("Number is even.");
            } else {
                System.out.println("Number is odd.");
            }

        } else {
            // Execute if num is not greater than 0
            System.out.println("Number is non-positive.");
        }
    }
}

Output
Number is positive.
Number is even.

Nested If Else Statement in Python:

Here are the implementation of Nested if else statement in python language:

Python3
# Declare and initialize the variable num
num = 10

# Outer if-else statement to check if num is greater than 0
if num > 0:
    print("Number is positive.")

    # Nested if-else statement to check if num is even or odd
    if num % 2 == 0:
        print("Number is even.")
    else:
        print("Number is odd.")

else:
    # Execute if num is not greater than 0
    print("Number is non-positive.")

Output
Number is positive.
Number is even.

Nested If Else Statement in C#:

Here are the implementation of Nested if else statement in C# language:

C#
using System;

class Program {
    static void Main(string[] args) {
        // Declare and initialize the variable num
        int num = 10;

        // Outer if-else statement to check if num is greater than 0
        if (num > 0) {
            Console.WriteLine("Number is positive.");

            // Nested if-else statement to check if num is even or odd
            if (num % 2 == 0) {
                Console.WriteLine("Number is even.");
            } else {
                Console.WriteLine("Number is odd.");
            }

        } else {
            // Execute if num is not greater than 0
            Console.WriteLine("Number is non-positive.");
        }
    }
}

Output
Number is positive.
Number is even.

Nested If Else Statement in JavaScript:

Here are the implementation of Nested if else statement in javascript language:

JavaScript
// Declare and initialize the variable num
let num = 10;

// Outer if-else statement to check if num is greater than 0
if (num > 0) {
    console.log("Number is positive.");

    // Nested if-else statement to check if num is even or odd
    if (num % 2 === 0) {
        console.log("Number is even.");
    } else {
        console.log("Number is odd.");
    }

} else {
    // Execute if num is not greater than 0
    console.log("Number is non-positive.");
}

Output
Number is positive.
Number is even.

Best Practices of Nested If Else Statement:

  • Keep it Simple: Don’t make your if else chains too long or complicated.
  • Use Clear Conditions: Use descriptive conditions so anyone reading your code can understand what’s happening.
  • Avoid Redundancy: Don’t repeat the same conditions unnecessarily.
  • Exit Early: Use return or break to exit the if else chain as soon as possible.
  • Consider Alternatives: Sometimes, using ternary operators or switch-case statements can make your code clearer.
  • Add Comments: If your logic is complex, explain it with comments so others (and your future self) can understand.

Use Cases of Nested If Else Statement:

  • Grading System: If a student’s score is greater than or equal to 90, they get an ‘A’. If not, check if it’s greater than or equal to 80 for a ‘B’, and so on.
  • Shopping Cart Discounts: If the user is a premium member, apply a 10% discount. If not, check if the total exceeds a certain amount for a 5% discount.
  • Authentication and Authorization: If the user’s credentials are valid, check their role. Depending on the role, grant access to different parts of the system.
  • Weather Forecast: If the temperature is above 30°C, it’s hot. If not, check if it’s between 20-30°C for a moderate forecast, and so on.
  • Game Development: If the player’s health is less than or equal to 0, they lose the game. If not, check if they have enough ammo to continue fighting.

Conclusion:

Use nested if else statements in programming when you need to evaluate conditions within other conditions. It helps you handle complex scenarios by branching your code based on various possibilities.



Similar Reads

If Else Statement in Programming
An if else statement in programming is a basic programming technique that allows you to make decisions based on certain conditions. It allows your program to execute different pieces of code depending on whether the specified condition evaluates to true or false. This capability is crucial in building dynamic and functional applications. Table of C
5 min read
If Else If Statement in Programming
If else if statement in programming allows you to check multiple conditions sequentially and execute different blocks of code based on those conditions. It's a way to handle various cases and make decisions within a program efficiently. Table of Content What is If Else If Statement?Syntax of If Else If StatementIf Else If Statement in CIf Else If S
4 min read
If Else Ladder in Programming
The If Else Ladder in programming refers to a series of if else statements structured in a cascading manner. It allows for sequential evaluation of multiple conditions, where each condition is checked in order. If a condition evaluates to true, the corresponding block of code is executed, and if none of the conditions are true, the other block at t
5 min read
If statement in Programming
An if statement is a fundamental control structure in programming languages that allows you to execute specific code blocks based on whether a condition is true or false. It is used to make decisions and control the flow of execution in your program. Table of Content What is an If Statement?Example of If Statement in ProgrammingConditional Operator
9 min read
Goto Statement in Programming
Goto statement is a control flow statement present in certain programming languages like C and C++. It enables programmers to transfer program control to a labeled section of code within the same function or block. Despite its availability, its usage is often discouraged in modern programming practices due to its potential to complicate code struct
3 min read
Switch statement in Programming
Switch statement in programming enables the execution of different code blocks based on the value of an expression, providing a structured approach to handle multiple cases efficiently. It enhances code readability and simplifies decision-making processes, making it a valuable tool for managing program flow and facilitating branching logic in softw
6 min read
Break vs Continue Statement in Programming
Break and Continue statements are the keywords that are used always within a loop. The purpose of a break and continue statement is to stop a running loop or to continue a particular iteration. In this article we will see what are the break and continue statements, what is their use and what are the differences between them. Break Statement:A break
4 min read
Nested Loops in Programming
In programming, Nested Loops occur when one loop is placed inside another. These loops are quite useful in day-to-day programming to iterate over complex data structures with more than one dimension, such as a list of lists or a grid. In this article, we will learn about the basics of nested loops and how they are used in different programming lang
6 min read
Can we write a print statement within if parentheses?
If-Else is a decision-making statement, where the result will be either true or false. If the statement accepts boolean values – if the value is true then it will execute the block of statements below it otherwise not. If no curly braces '{' and '}' is provides after if(condition) then by default if statement will consider the immediately below sta
1 min read
Which Programming Language to Choose?
One of the most annoying question today is which programming language should be chosen for the sake of education/career or anything. Answer for this question to many programmers ends up with C or C++, or mostly Java but why C? why C++? Why Java?. Today many software exists, to solve a problem but also to interfere with another software. nowadays in
4 min read
Article Tags :