|
|
Switch Statments Let's say you wish to write a program that will calculate a person's letter grade based on their test scores. You could do it like this:
#include<iostream.h>
void main()
{
int score;
cout « "Enter the test score: "« endl;
cin» score;
if(score>100) cout « "out of range" « endl;
else if (score>=90) cout«'A'« endl;
else if (score>=80) cout«'B'« endl;
else if (score>=70) cout«'C'« endl;
else if (score>=60) cout«'D'« endl;
else if (score>=0) cout«'F'« endl;
else cout« "Error: score out of range."« endl;
}
When you start to use a lot of else if statements, your program can look a little confusing. Another way to do the same thing is to use the switch statement. A switch statement looks like this:
switch(choice)
{
case 1: statement; break;
case 2: statement; break;
case 3: statement; break;
}
You offer the user a series of choices and the program offers a response based on their choice. Here's how we can re-do our grade program using switch statements:
#include<iostream.h>
void main()
{
int score;
cout« "Enter the test score: "« endl;
cin» score;
switch(score/10){
case 10:
case 9: cout«'A'« endl; break;
case 8: cout«'B'« endl; break;
case 7: cout«'C'« endl; break;
case 6: cout«'D'« endl; break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0: cout«'F'« endl; break;
default: cout«"Error: score out of range."« endl;
}
}
You can use switch statements do all sorts of things. Here's an example of using switch statments of create a menu:
#include<iostream.h>
void main()
{
char letter;
cout«"\t\t\t--------------MENU-------------"« endl;
cout«"\t\t\t-----A: first menu item--------"« endl;
cout«"\t\t\t-----B: first menu item--------"« endl;
cout«"\t\t\t-----C: first menu item--------"« endl;
cout«"\t\t\t-----D: first menu item--------"« endl;
cout«"\t\t\t-----E: first menu item--------"« endl;
cout«"\t\t\tEnter a capital letter to select one"« endl;
cin» letter;
switch(letter){
case 'A': cout«"The first was selected."« endl; break;
case 'B': cout«"The second was selected."« endl; break;
case 'C': cout«"The third was selected."« endl; break;
case 'D': cout«"The fourth was selected."« endl; break;
case 'E': cout«"The fifth was selected."« endl; break;
default: cout« "You didn't pick one."« endl;
}
}
AssignmentWrite a program that displays the signs of the horoscope. Create a series of whacky responses to match whatever choice they made. Due: Feb 21. |