Why do we use "else if", if we can do the same thing using "if" conditional statement ?? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 5

Why do we use "else if", if we can do the same thing using "if" conditional statement ??

22nd Aug 2019, 4:01 AM
Snigdh
Snigdh - avatar
10 Antworten
+ 12
If u use all the where if statement the compiler gonna check all the statements.. Whereas If u use if-else the compiler gonna stop when it found one statement true.. Moral of the story is..it saves executives time Thank you
22nd Aug 2019, 2:14 PM
Bhavik Bhuva
Bhavik Bhuva - avatar
+ 15
They are not entirely the same. if (a) { } if (b) { } The above two statements will both execute if a and b are true. We say that these two statements are independent. if (a) { } else if (b) { } In this case, if a is true, the else statement will never execute although b is true. The else statement which evaluates b will only be executed if a is false.
22nd Aug 2019, 4:08 AM
Fermi
Fermi - avatar
+ 6
Sometimes the code looks neater with else if, but Fermi mentioned the main reason.
22nd Aug 2019, 9:04 AM
Sonic
Sonic - avatar
+ 5
Result will be the same, if you use 2 - if conditions or if-elseif are used. But only thing is that, if you use 2 - if's then both conditions needs to be evaluated during run-time. Which will affect performance in time critical systems. So, it preferred to use if-elseif whenever possible... Hope this helps...!!!
22nd Aug 2019, 5:00 AM
Kuri
Kuri - avatar
+ 3
If we use if(statement) {do this;} if(statement) {do this;} It checks both the conditions even if the first one is true. This takes more time. if(statement){do this;} else if(statement){do this;} Here, control will go to the else if only if the first if is false.
23rd Aug 2019, 12:23 PM
T I
+ 2
You are right, every ÔÇ×else ifÔÇť condition could be rewritten as a nested sequence of if-conditions, but it would be much more complex.
22nd Aug 2019, 4:39 AM
Michael
Michael - avatar
+ 2
The execution speed of "elif" statement is more than "if" statement
23rd Aug 2019, 5:40 AM
PRABHMEHAR
PRABHMEHAR - avatar
+ 2
a=15; if(a>5){ print a; }else if(a>10){ print a; } Output: 5 a=15; if(a>5){ print a; }if(a>10){ print a; } Output: 5 5
23rd Aug 2019, 1:16 PM
Md Jahid Hasan Marof
Md Jahid Hasan Marof - avatar
0
To check the conditions of multiple statement in a easy manner and short program. Whereas in if we can't compare multiple statement with different different output and if we do, it's take too much time as well as lengthy program.
24th Aug 2019, 9:20 PM
Akash Khanpara
Akash Khanpara - avatar
0
Yes you can but i think the else if statement is better
25th Aug 2019, 10:21 PM
jeffrey ogbonnaya
jeffrey ogbonnaya - avatar