- 1

Confusion

What is the difference between if-else if and nested if-else can anybody?

28th Feb 2020, 8:18 PM
Venky K Nannur
Venky K  Nannur - avatar
4 Respuestas
+ 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
28th Feb 2020, 8:30 PM
Seb TheS
Seb TheS - avatar
+ 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.
29th Feb 2020, 12:40 AM
Denise Roßberg
Denise Roßberg - avatar
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.
28th Feb 2020, 8:46 PM
Seb TheS
Seb TheS - avatar