+ 1
What is the difference between if else and else if statement?
I found their work same.
2 odpowiedzi
+ 1
if-else will run only the code in the if block, if the condition returns true. The else block, if present, will only run if the condition returns false.
if-else if-else like the if-else will only run 1 of the code blocks. If the if condition returns true then its code block is ran and all others are skipped. If it returns false then the 2nd condition is evaluated and that code block will run if true, then all others are skipped. If there are more else-if conditions they will be checked in a top down fashion in the same manner. If all conditions return false the else block will run if present.
+ 2
See this example. We can write if statement inside else part that is called else if statement.
if() {
} else {
if() {
}
}
We can write any number of if else and else if statement. See the another example
if(age > 65) {
// senior citizens
} else {
if(age < 65 && age > 50) {
//old
} else {
if(age < 50 && age > 20) {
//young
} else {
//youngest
}
}
}