Nested If Else Statement in Programming
Last Updated :
10 Apr, 2024
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;
}
OutputNumber 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;
}
OutputNumber 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.");
}
}
}
OutputNumber 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.")
OutputNumber 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.");
}
}
}
OutputNumber 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.");
}
OutputNumber 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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read