+ 2
What is the difference between if statement and switch?
3 Answers
+ 3
If u have many cases u should use switch case instead of writing else if many times
+ 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!
+ 3
In switch statement you can't use the relational operators like '<' and '>'
But, you can use in if statement.