- 1
Confusion
What is the difference between if-else if and nested if-else can anybody?
4 Antworten
+ 1
Do you mean difference between:
if () {}
else if () {}
And:
if () {}
else {
if () {}
}
?
There is no practical difference.
You might know that if statements:
if () {statement;}
Can sometimes be written as:
if () statement;
Same works for else statements.
This:
if () {}
else {
if () {}
}
can be written as:
if () {}
else if () {}
And you can conclude that else if statements are actually else statements nested with if statement:
https://www.sololearn.com/discuss/1952469/?ref=app
+ 1
Venky K Nannur
I will try to explain it with an example.
int age = 18;
if(age < 18){
//do someting
}
No else. Means if age >= 18 nothing will happens.
if(age < 18){
//do something
}else{
//do something
}
Here you handle the cases when age < 18 and if not it executes the else block.
if(age < 18){
if(age < 13){
//do something
}
}
This is an example of an nested if if statement. You can also add else cases for both.
It executes the code in the inner if statement only of age < 18 is true and age < 13 is true.
You can replace //do something with print statements to get more clarification.
0
Shortly this:
if (condition1) {statements1;}
else {
if (condition2) {statements2;}
}
Is always equivalent to this:
if (condition1) {statements1;}
else if (condition2) {statements2;}
But the second way is more readable.