Jul 24, 2011 at 8:17pm UTC
What is the difference of if and else loops compared to switch?
What are the uses for both?
Jul 24, 2011 at 8:41pm UTC
well, let me preempt this by saying I could be wrong; I'm just trying to help.
First of all, if, else, else if and switch aren't really loops, they're conditionals.
If's, if elses and elses check one condition at a time.
if (a = b)
then condition happens
else [implied to mean a != b]
then other condition happens
switch statements are for allowing users to input different answers and getting different results
switch[gradeScale]
case "A":
cout << "great job";
break;
case "B":
cout << "good job";
break;
case "C":
cout << "ok job";
break;
and so on...
you could do an if / else if statement for this as well, but if ends up pretty complex eventually.
if (gradeScale == "A")
cout << "great job";
else
if (gradeScale == "B")
cout << "good job";
else
if (gradeScale == "c")
cout << "ok job";
else
.. and so on...
if just makes things a little easier to read and understand.
Jul 24, 2011 at 8:41pm UTC
They're practically interchangeable. if-else statements are a bit more versatile, you can test multiple boolean conditions using && and || whereas I don't think you can do that with switch.
Jul 24, 2011 at 9:01pm UTC
with switch statements you can fall through by leaving out the break.