⬅ Previous Topic
Conditional Statements - if, elseNext Topic ⮕
Switch Case Logic⬅ Previous Topic
Conditional Statements - if, elseNext Topic ⮕
Switch Case LogicNested 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.
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.
if (condition1) {
// do something
if (condition2) {
// do something more
} else {
// another path
}
} else {
// fallback path
}
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
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.
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
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.
⬅ Previous Topic
Conditional Statements - if, elseNext Topic ⮕
Switch Case LogicYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.