Presentation is loading. Please wait.

Presentation is loading. Please wait.

Switch Case Structures

Similar presentations


Presentation on theme: "Switch Case Structures"— Presentation transcript:

1 Switch Case Structures
Lecture 9 Narrator: Lecture 9: Switch Case Selection Structures Winter Quarter

2 Switch Multiple Selection Structure
A multiple selection structure is useful when an algorithm contains a series of decisions in which a variable or expression is tested separately for one of several possible integral values. Each integral value represents a different action to be taken in the algorithm. C provides the switch multiple selection structure to implement this type of decision making. Instructor: The switch (switch case) structure is useful when testing a certain variable for multiple cases. It is also useful when comparing a variable against a character (as opposed to numerical) value. An example of this will be shown in this lecture. Narrator: A multiple selection structure is useful when an algorithm contains a series of decisions in which the same variable or expression is tested separately for several possible integral variables. Each of these values represents a different action to be taken. The switch (or switch case) structure is useful when testing a certain variable for multiple cases. It is also useful when comparing a variable against a character (as opposed to numerical) value. An example of this will be shown in this lecture. Winter Quarter

3 Switch-Case Structures
The switch - case syntax is: switch (integer expression test value) { case case _1_fixed_value : action(s) ; case case_2_fixed_value : default : } Note use of colon! Instructor/Narrator: The switch case structure is given on this slide. The colon is used to separate the case from the actions to be completed. Within each case the action(s) do not have to be surrounded by braces when there is more than one. We will now discuss the details of this structure. Winter Quarter

4 Switch-Case Structures
The switch is the "controlling expression" Can only be used with constant integer expressions. Remember, a single character is a small positive integer. The expression appears in ( ) The case is a "label" The label must be followed by a " : " Braces, { }, not required around statements Instructor: The switch is simply the variable that will be used to determine true or false relationships in the cases. Each case contains a value that the switch will be compared to. If the switch is numerically equal to the case the expression(s) in that case will be executed along with all the statements below this expression. Narrator: The switch is the controlling expression, which will be tested for the multiple cases. It can only be used with constant integer expressions, but remember a single character is also considered a small positive integer by the computer. The switch expression appears in parentheses. The case is a label, or the value that the expression is tested against. The label must be followed by a colon and braces are not required in this structure. Winter Quarter

5 Switch-Case Structures
Unlike if-else if-else structures, when the value in a case matches the test value, all of the actions in the rest of the structure take place. This is shown in the following program where the user enters a value that matches the first case and every action in the structure is executed. Instructor: This problem has a solution: use of the break; command, but for now allow the student to understand how the basic switch-case structure works in the following example. Narrator: Unlike the if / else if /else structure where only one statement block is executed and the rest are skipped, when a value in a case matches the test value, all the actions in the REST of the structure take place. The following program will demonstrate when a value matches the first case, every action in the entire structure is executed. Winter Quarter

6 A Sample Program to Illustrate Switch-Case
Problem: Write a program to ask the user to enter his/her letter grade and then respond with an appropriate message regarding his/her academic status. Instructor: At this point you may wish to ask the students to come up with a few of the simple components necessary to complete this program (and thus developing a sort of pseudo-code, allowing the students to practice their logic skills). An algorithm is available on the next slide. Narrator: The problem given is to write a program to ask the user to enter his or her letter grade, and then allow the program to respond with an appropriate message regarding his or her academic status. You may wish to create your own pseudo-code before looking at the next slide to practice your pseudo-code skills. Winter Quarter

7 A Sample Program to Illustrate Switch-Case
Algorithm: 1. Set up the environment 2. Prompt user to enter his/her letter grade 3. Get user’s response 4. If grade is a or A say “Good Job” and go to 9 5. If grade is b or B say “Pretty good” and go to 9 6. If grade is c or C say “Better get to work” and go to 9 7 If grade is d or D say “You are in trouble” and go to 9 8. Say “You are failing” 9. Terminate program Narrator: Here is the algorithm used to develop the program on the next slide. The section we are most concerned with involves the selection structure around determining what to do with the user’s response. The user’s response will be our switch. The different cases will be the values of a through d. Winter Quarter

8 A Sample Program to Illustrate Switch-Case
/* This program associates a letter grade with a message appropriate to the score */ #include <stdio.h> void main ( ) { char grade ; printf ("Enter your current letter grade\n") ; grade = getchar ( ) ; Instructor: Note the use of getchar() in this case to get a single character from the keyboard. Narrator: The beginning of the program initializes the variables needed, then asks for the user’s input and acquires it via the getchar() command, which gets a single character from the keyboard. Winter Quarter

9 A Sample Program to Illustrate Switch-Case
switch (grade) { case ('a') : case ('A') : printf ("Good Job!\n") ; case ('b') : case ('B') : printf ("Pretty good.\n") ; Instructor/Narrator: Note that no assumption was made whether the letter would be lower case or capitalized, so we must handle both cases. Also since all code below whatever case is evaluated to be equal to the variable grade is executed, even if the user enters an “a” or “A”, the program will still execute the printf(“Good Job!\n”); since it is below both of the cases. Also note that each case doesn’t require a statement after it. Winter Quarter

10 A Sample Program to Illustrate Switch-Case
case ('c') : case ('C') : printf ("Better get to work.\n") ; case ('d') : case ('D') : printf ("You are in trouble.\n") ; default : printf ("You are failing!!\n") ; } /* End of switch-case structure */ } /* End of main program */ Instructor/Narrator: The rest of the switch-case structure is shown here. Note the default case is ALWAYS executed even if all the above cases are not found to be equal to the switch. It acts as a catch-all to handle any previously unhanded “cases.” Winter Quarter

11 Switch-Case Structures Resultant Output from Grade Program
/* The following results are produced when the user enters an "A" as input to the program prompt. */ Good Job! Pretty good. Better get to work. You are in trouble. You are failing! Instructor: Point out the problem in the structure of the program, since the A is at the beginning of the code it will output ALL the messages (since they are all lower in the switch-case structure). A “b” or “B” input will begin with “Pretty good.” and print the lines below this, and so one for C, D, E, etc. If another letter (such as “Z”) is input, only the default “You are failing!” line will be displayed. Narrator: Since the input of the letter A is handled at the beginning of the code it will output ALL the messages (since they are all lower in the switch-case structure). A “b” or “B” input will begin with “Pretty good.” and print the lines below this, and so one for C, D, E, etc. If another letter (such as “Z”) is input, only the default “You are failing!” line will be displayed. Winter Quarter

12 Switch-Case Structures
break ; The problems with the previous program can be corrected by use of the break statement. It can be used in either a repetition structure or a selection structure to break out of (that is, to exit from) the structure. The syntax is: The following program is the previous one with the addition of the break statements. Instructor: The solution is introduced! Note the break; can also be used in loops (repetition structures) and standard if/else if/else structures in addition to the switch-case structure. Narrator: A solution to this problem does exist though. The break command can be used in either a repetition or selection structure to break out, or exit, the structure. The syntax is simple break ;. The previous program can now be fixed with the addition of break statements. Winter Quarter

13 Fixed Program using Switch-Case Structures
#include <stdio.h> void main ( ) { int grade ; printf ("Enter your current letter grade\n") ; while ( ( grade = getchar ( ) ) != EOF) switch (grade) case ('a') : case ('A') : printf ("Good Job!\n") ; break ; Instructor: This program introduces other structures also. The use if a while() loop is brought back again, this case with the loop containing a function and evaluation. Breaking this expression down into it’s separate commands: grade=getchar(): gets a character from the keyboard and places it in the variable grade (grade=getchar())!=EOF: evaluates the value placed in grade for the EOF (end of file) character, which is actually a control character while((grade=getchar())!=EOF): executes the statements in the braces as long as the contents evaluate TRUE (the EOF isn’t entered from the keyboard) { //statements } The next slide is a better visual description of the use of the break; command, since there are multiple cases on the slide. Narrator: The fixed program is shown here along with various other improvements. Another loop, called a while loop, is included so that the user may enter multiple grades and receive a response for each one. Inside the while loop the key is input from the keyboard and checked for EOF, at which point it would exit the while() loop and terminate the program. Winter Quarter

14 Fixed Program using Switch-Case Structures
case ('b') : case ('B') : printf ("Pretty good.\n") ; break ; case ('c') : case ('C') : printf ("Better get to work.\n") ; case ('d') : case ('D') : printf ("You are in trouble.\n") ; Instructor: Now it can be seen that after each case’s command there is a break; command, which tells the computer to break out of the switch-case structure. Narrator: This slide better demonstrates the addition of the break; command. Notice after the end of each case a break will exit the structure instead of executing every statement like the previous example. Winter Quarter

15 Fixed Program using Switch-Case Structures
case ('f') : case ('F'): printf ("You are failing!!\n") ; break ; case (' ') : case ('\n') : default : printf ("Invalid grade. Try again.\n") ; } /* End of switch/case */ } /* End of while loop */ } /* End of "main" function */ Narrator: The default on this program is now set to check for invalid input, thus prompting the user to try again. Winter Quarter

16 Comments on Last Example Program
Use of the while repetition structure -- more discussion on repetition structures later this week. Use of the end-of-file, or EOF, test. Note that EOF (a DEFINED constant) is a negative integral value, usually a -1 on most (but not all) systems. (EOF is actually defined in the <stdio.h> header file.) Use of ints (instead of chars). Why? From the keyboard, a <return> <cntrl-d> generates an EOF signal on most UNIX systems. Instructor: int is used instead of char since we care about comparing the numerical variables (plus the switch-case can only compare numerical values, not text as we think of it). The result of value=putchar(); when value is of type int involves storing the numerical value of the character in value instead of the character itself. Since each character actually is stored in the computer as a unique numerical value this is perfectly valid. Students may visit for more information. Narrator: To summarize, we will cover repetition structures in the next lecture. A check for EOF was evaluated in this while loop. EOF is typically defined as a -1 on most systems. This is actually defined in the <stdio.h> header file. Why did we use ints in stead of chars? int is used instead of char since we care about comparing the numerical variables (plus the switch-case can only compare numerical values, not text as we think of it). The result of value=putchar(); when value is of type int involves storing the numerical value of the character in value instead of the character itself. Since each character actually is stored in the computer as a unique numerical value this is perfectly valid. Finally, to generate a EOF signal on most UNIX systems the key combination of <return> <cntrl-d> can be used. Winter Quarter

17 Comments on Last Example Program
The statements: case (' ') : case ('\n') : break ; were used to clear the keyboard input buffer. Another way to clear it is with the statement: fflush (stdin) ; This statement can prove very useful in today’s daily assignment. Instructor: The typical way to clear a buffer is to use fflush() and not the switch-case method. The input buffer is typically flushed before the user is required to supply input. Narrator: One of the final cases, shown again here, was actually used to clear the keyboard input buffer. Another more common way to do this though is with the fflush() function. In this case we would fflush() the stdin stream. You can also use fflush with any other standard stream. This may prove useful in today’s assignment. Winter Quarter

18 Comments on Last Example Program
Example of use of fflush char figure; float size; printf ("Enter figure type>") ; fflush (stdin) ; scanf ("%c", &figure) ; //or figure=getchar( ); printf ("Enter size of figure>") ; fflush (stdin); scanf ("%f", &size); Instructor: Point out that fflush() is used JUST BEFORE a scanf in this case (not after). Using a fflush() right after a scanf may actually flush the buffer of the user’s input you actually wanted to keep. Narrator: fflush() is used in an example here. Notice it is used before each scanf statement. fflush() shouldn’t be used directly after a scanf() since the program may then flush the user’s data from the stream before the program uses it. Winter Quarter

19 Assignment E8 Use a switch-case structure to select from among the shapes for which calculation are to be made. May use just first character of shape name to select which calculation to make. Program only does one shape, and then exits. No looping required for today's assignment. Instructor: If a student is having trouble understanding the entire structure of the program, have him or her develop an algorithm for each separate shape, then algorithm for determining which shape to calculate. This should help the student put the pieces together. Narrator: Today’s assignment will make use of the switch structure to select from among various shapes a calculation can be made for. Using the first character of the shape name is satisfactory for selection. No loop is required for this program. Your program should ask the user to select one shape, input the values necessary for the calculation, display the result, then exit. Winter Quarter


Download ppt "Switch Case Structures"

Similar presentations


Ads by Google