+ 2

What is the difference between if statement and switch?

11th Jan 2022, 8:09 PM
Loo Student
3 Answers
+ 3
If u have many cases u should use switch case instead of writing else if many times
11th Jan 2022, 8:12 PM
Muhammad Galhoum
Muhammad Galhoum - avatar
+ 3
Switch is if you have a list of different options for outcomes but all of the same type. Often, days of the week are used, but it could be something like animals or a sequence of numbers. "If" or "else if" could handle this too but would take more coding, as Muhammad said. E.g. (forgive the basic/sloppy psuedo-code) Switch(animals) Case 1: cat //code Case 2: snake // code Case n: other animal //code Or Switch(number sequence) Case 1: 1357 //code Case 2: 14159 //code Case n: other sequence of numbers //code Is similar to: If(animal == cat) //code Else if(animal == snake) //code Else if(animal == other animal) //code And so on... I hope that helps!
11th Jan 2022, 8:48 PM
Ausgrindtube
Ausgrindtube - avatar
+ 3
In switch statement you can't use the relational operators like '<' and '>' But, you can use in if statement.
12th Jan 2022, 1:43 AM
Ananya | Inactive |
Ananya | Inactive | - avatar