For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
How do you handle more than one condition inside an if block in C?
That’s where a nested if else statement in C becomes useful.
A nested if else statement in C lets you place one if or else if block inside another. This is helpful when decisions depend on more than one condition. You can create step-by-step logic for complex scenarios—like grading systems, login validations, or multi-level checks in real programs.
In this tutorial, you'll learn how to write and structure a nested if else statement in C. We'll walk through its syntax, flow, and indentation rules to avoid confusion. Using easy-to-understand examples, you’ll see how nested conditions execute and what pitfalls to avoid.
By the end, you'll know exactly when and how to use a nested if else statement in C to make your programs smarter and more responsive. Want to sharpen your coding fundamentals even further? Explore our Software Engineering Courses built for real-world application and career growth.
A nested if-else statement in C allows you to check multiple conditions in a hierarchical way, where an if-else structure is placed inside another if or else block. This makes it possible to evaluate complex conditions in a single decision-making structure.
Here’s the basic nested if-else statement syntax:
if (condition1) {
if (condition2) {
// Action if both conditions are true
} else {
// Action if condition1 is true and condition2 is false
}
} else {
// Action if condition1 is false
}
Explanation of the Structure:
Ready to move beyond C programming and unlock new career opportunities? We've curated these forward-looking courses specifically to enhance your professional growth:
To visualize the flow, let's look at a simple flowchart of a nested if-else statement:
Let’s look at the nested if-else statement with an example. This example will check whether a number is positive or negative and, if positive, whether it's even or odd.
#include <stdio.h>
int main() {
int number = 12; // Initial number
if (number > 0) { // Outer if: Check if the number is positive
if (number % 2 == 0) { // Inner if: Check if the positive number is even
printf("The number is positive and even.\n");
} else { // Inner else: If the positive number is odd
printf("The number is positive and odd.\n");
}
} else if (number < 0) { // Outer else-if: Check if the number is negative
printf("The number is negative.\n");
} else { // Else for zero
printf("The number is zero.\n");
}
return 0;
}
Output:
The number is positive and even.
Explanation:
Nested if-else statements are useful in real-world scenarios where conditions depend on each other. Read on to know when to use them.
A nested if-else statement is particularly useful when you need to evaluate multiple conditional statements that depend on each other.
This allows you to handle more complex logic in your program, making it ideal for situations where a decision needs to be based on several factors.
Use Cases
Some common real-world situations where nested if-else statements with examples are beneficial include:
Now, let’s take a closer look at an advanced real-life implementation of a nested if-else statement example. In this example, we will check whether a person is eligible for a loan based on their age and income.
The eligibility criteria are:
#include <stdio.h>
int main() {
int age = 25; // Person's age
int income = 2500; // Person's monthly income
int credit_score = 720; // Person's credit score
if (age >= 18 && age <= 60) { // Check if age is valid
if (income >= 2000) { // Check if income is valid
if (credit_score >= 700) { // Check if credit score is sufficient
printf("Loan Approved.\n");
} else { // Credit score is less than 700
printf("Loan Denied: Low Credit Score.\n");
}
} else { // Income is less than $2000
printf("Loan Denied: Insufficient Income.\n");
}
} else { // Age is outside valid range
printf("Loan Denied: Invalid Age.\n");
}
return 0;
}
Output:
Loan Approved.
Explanation:
Also Read: Top 3 Open Source Projects for C [For Beginners To Try]
Now that you know when to make the most of a nested if-else statement, let’s tackle some common pitfalls and how to steer clear of them.
It's easy to make mistakes when working with nested if-else statement syntax. Below are some common pitfalls and best practices for avoiding them to ensure that your code remains clean, efficient, and easy to maintain.
One of the most common mistakes is forgetting to properly close curly braces, which can lead to syntax errors or unexpected behavior. Always ensure that every opening { has a corresponding closing }.
Example:
if (condition) {
// code
// Missing closing brace here
Consistent indentation is critical for readability. When nesting if-else statements, improper indentation can make the logic hard to follow. Always use consistent indentation (e.g., 4 spaces or a tab).
Example:
if (condition) {
if (anotherCondition) {
// code
}
}
Deeply nested if-else statements can make code difficult to read and debug. Limit the nesting depth to avoid confusion. If your logic is becoming too complex, refactor it into smaller, more manageable functions.
Example:
if (condition1) {
if (condition2) {
if (condition3) {
// Too deep – consider refactoring
}
}
}
Use consistent and proper indentation to clearly demarcate different blocks of logic. This makes the flow of your code easier to understand.
Example:
if (condition1) {
if (condition2) {
// Inner block for condition2
} else {
// Action for condition2 false
}
} else {
// Action for condition1 false
}
Keep the nesting depth to a minimum. If you go more than three levels deep, consider refactoring the logic into separate functions to improve readability and maintainability.
Example:
Instead of:
if (x > 0) {
if (y < 10) {
if (z == 5) {
// Deeply nested logic
}
}
}
Refactor into:
if (x > 0 && y < 10) {
processZ(z);
}
Break down complicated logic into smaller, reusable functions. This will not only make your code easier to follow but will also reduce redundancy and improve maintainability.
Example:
Instead of:
if (num > 0) {
if (num % 2 == 0) {
// Action for positive and even number
}
}
Refactor into:
if (num > 0) {
checkEven(num);
}
void checkEven(int num) {
if (num % 2 == 0) {
// Action for even number
}
}
Ensure that all possible conditions are checked, especially when dealing with user input or external data. Edge cases like null values, boundary conditions, or unexpected inputs can lead to logical errors.
Example:
if (num == NULL) {
printf("Error: Null value detected.");
} else {
// Proceed with further checks
}
If similar conditions are being checked repeatedly, it’s better to refactor and remove redundancy. This makes your logic clearer and more efficient.
Example:
Instead of:
if (num == 1) {
// action
} else if (num == 2) {
// action
}
Use:
switch (num) {
case 1:
case 2:
// action for both 1 and 2
break;
}
else if instead of multiple if statements makes it clear that only one condition will be executed. This improves the readability and intent of your code.
Example:
if (num == 1) {
// action
} else if (num == 2) {
// action
} else {
// action if neither condition is met
}
Also Read: Top 25+ C Programming Projects for Beginners and Professionals
Nested if-else statement syntax can quickly become messy if not managed properly. By following best practices, you can ensure your code remains clean, readable, and maintainable.
1. What is a nested if else in C?
a) Multiple if statements after else if
b) if or else block inside another if or else block
c) Independent if-else chains
d) A loop inside an if block
2. Which of the following is a correct syntax for nested if else?
a) if (a) else if (b) if (c)
b) if (a) { if (b) { ... } }
c) else if (a) { if (b) }
d) if else if (a && b)
3. What is the output of this code?
int x = 5;
if(x > 0)
if(x > 10)
printf("A");
else
printf("B");
a) A
b) B
c) Error
d) No output
4. Nested if else is mostly used when:
a) You need to check multiple unrelated conditions
b) You want to evaluate a simple boolean
c) Multiple dependent conditions must be checked in order
d) To create infinite loops
5. What will be the output of this code?
int x = 8;
if(x < 10)
if(x > 5)
printf("Yes");
else
printf("No");
a) Yes
b) No
c) Nothing
d) Error
6. Which mistake leads to confusing nested if-else results?
a) Missing brackets {}
b) Too many variables
c) Use of break
d) Absence of scanf
7. What helps clearly define blocks in nested if else?
a) Semicolons
b) Indentation
c) Brackets {}
d) Goto statements
8. In nested if else, which block executes first?
a) Else
b) Outer if
c) Inner else
d) Outer else
9. You have this logic:
if(a > b)
if(a > c)
printf("A is largest");
else
printf("C is largest");
else
if(b > c)
printf("B is largest");
else
printf("C is largest");
What is the purpose of this nested if else?
a) Check equality of numbers
b) Find the largest of three numbers
c) Count even numbers
d) Return negative values
10. A candidate omits curly braces in this nested if else:
if(a > 0)
if(a < 100)
printf("Valid");
else
printf("Invalid");
What is a possible risk?
a) Logical error
b) Compile error
c) Segmentation fault
d) Stack overflow
11. In which scenario would nested if else be preferred over switch case?
a) Multiple values of the same variable
b) Ranges and compound conditions
c) Exact string matching
d) When enum values are checked
Now that you’ve tested your knowledge of nested if-else statements, it's time to solidify your understanding with expert-led learning. Upgrading your skills is essential, and upGrad offers comprehensive courses to help you master C programming, including working with nested conditions.
Explore nested if-else statements and other advanced topics in C programming. upGrad provides interactive learning and hands-on projects to enhance your problem-solving abilities.
Check out upGrad’s courses to deepen your expertise:
You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Similar Reads:
Explore C Tutorials: From Beginner Concepts to Advanced Techniques
Array in C: Introduction, Declaration, Initialisation and More
Exploring Array of Pointers in C: A Beginner's Guide
What is C Function Call Stack: A Complete Tutorial
Constant Pointer in C: The Fundamentals and Best Practices
Find Out About Data Structures in C and How to Use Them?
The nested if-else statement syntax allows you to place one if-else statement inside another, enabling more complex decision-making by evaluating multiple conditions.
Yes, you can check as many conditions as needed. A nested if-else statement with example can handle multiple conditions within the inner and outer blocks, providing more flexibility in logic.
The nested if-else statement syntax provides a clear, structured way to handle complex decision-making, ensuring that only one condition is evaluated at a time and improving the readability of your code.
Avoid using nested if-else statements with examples when you have too many nested levels, as it can lead to code that is difficult to read and maintain. Consider alternatives like switch statements or refactoring.
Ensure that your nested if-else statement syntax accounts for all possible conditions, including boundary cases. Use proper logic to check for edge cases, such as invalid inputs or extreme values.
Yes, you can use jump statements like break or return inside a nested if-else statement to exit early, but they should be used carefully to maintain clarity in your logic.
It's best to limit nesting to 2-3 levels. If you need more, consider breaking the logic into separate functions to maintain readability and avoid cluttering your code with excessive nested if-else statement syntax.
Yes, nested if-else statements with example are ideal for validating multiple user inputs, such as checking if an age is within a valid range or if a password meets the required conditions.
Optimize performance by reducing the depth of nesting and ensuring that the most likely conditions are checked first, minimizing the number of evaluations needed in the nested if-else statement.
Use nested if-else statements with examples when dealing with complex conditions that involve ranges, logical operators, or multiple criteria. A switch statement is better for evaluating one variable against multiple constant values.
Keep your nested if-else statement syntax simple, avoid deep nesting, and use proper indentation to make the code easy to read. Refactor complex logic into smaller, reusable functions for better maintainability.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author|900 articles published
Previous
Next
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.