The switch Statement
Occasionally, an algorithm will contain a series of decisions in which a variable or expression is tested separately for each of the constant integral values it may assume, and different actions are taken. This is called multiple selection. C provides the switch multiple-selection statement to handle such decision making. The switch statement consists of a series of case labels, an optional default case and statements to execute for each case. © by Pearson Education, Inc. All Rights Reserved. Dr. Soha S. Zaghloul2
switch (identifier) { case ‘value1’: block of statements 1; break; case ‘value2’: block of statements 2; break; … case ‘value n’: block of statements n; break; default: block of statements; break; } Dr. Soha S. Zaghloul3
break is used to exit the switch statement. default is used if the variable did not satisfy any value of the listed cases. Dr. Soha S. Zaghloul4
Write a program that displays a menu and prints a message for each selection made by the user. The program should prompt the user in case of an invalid input. The menu to be displayed is as follows: Enter your choice: ‘E’: Edit my program ‘C’: Compile my program ‘R’: Run my program Dr. Soha S. Zaghloul5
1.Display the menu 2.Get the input from the user 3.If the user entered ‘E’, then print “Calling the editor” 4.If the user entered ‘C’, then print “Calling the compiler” 5.If the user entered ‘R’, then print “The program starts execution” 6.For any other input, print “Invalid input” ALGORITHM Dr. Soha S. Zaghloul6
Dr. Soha S. Zaghloul7 START Display Menu READ choice choice = ‘E’ choice = ‘C’ choice = ‘R’ Print “Call Editor” Print “Call Compiler” Print “The program starts execution” Print “Invalid Input” END TRUE FALSE
1.Display the menu 2.Scanf choice 3.Switch for the value of choice: a.Case choice = ‘E’ printf (“Calling the Editor”) b.Break c.Case choice = ‘C’ printf (“Calling the Compiler”) d.Break e.Case choice = ‘R’ printf (“The program starts execution”) f.Break g.Otherwise printf (“Invalid input”); 4. End of program PSEUDOCODE Dr. Soha S. Zaghloul8
#include int main (void) { printf (“Enter your choice \n”); printf (“E: Edit \n”); printf (“C: Compile \n”); printf (“R: Run \n”); printf (“What do you want to do? “); } 1.Display the menu 2.Scanf choice 3.Switch for the value of choice: a.Case choice = ‘E’ printf (“Calling the Editor”) b.Break c.Case choice = ‘C’ printf (“Calling the Compiler”) d.Break e.Case choice = ‘R’ printf (“The program starts execution”) f.Break g.Otherwise printf (“Invalid input”); 4. End of program PSEUDOCODE Dr. Soha S. Zaghloul9
#include int main (void) { char choice; printf (“Enter your choice \n”); printf (“E: Edit \n”); printf (“C: Compile \n”); printf (“R: Run \n”); printf (“What do you want to do? “); scanf (“%c”, &choice); } 1.Display the menu 2.Scanf choice 3.Switch for the value of choice: a.Case choice = ‘E’ printf (“Calling the Editor”) b.Break c.Case choice = ‘C’ printf (“Calling the Compiler”) d.Break e.Case choice = ‘R’ printf (“The program starts execution”) f.Break g.Otherwise printf (“Invalid input”); 4. End of program PSEUDOCODE Dr. Soha S. Zaghloul10
Dr. Soha S. Zaghloul11 #include int main (void) { char choice; printf (“Enter your choice \n”); printf (“E: Edit \n”); printf (“C: Compile \n”); printf (“R: Run \n”); printf (“What do you want to do? \n“); scanf (“%c”, &choice); switch (choice) { case ‘E’: printf (“Calling the Editor \n”); break; case ‘C’: printf (“Calling the Compiler \n”); break; case ‘R’: printf (“The program starts execution \n”); break; default: printf (“Invalid Input \n”); break; } // end switch } 1.Display the menu 2.Scanf choice 3.Switch for the value of choice: a.Case choice = ‘E’ printf (“Calling the Editor”) b.Break c.Case choice = ‘C’ printf (“Calling the Compiler”) d.Break e.Case choice = ‘R’ printf (“The program starts execution”) f.Break g.Otherwise printf (“Invalid input”); 4. End of program PSEUDOCODE
#include int main (void) { char choice; printf (“Enter your choice \n”); printf (“E: Edit \n”); printf (“C: Compile \n”); printf (“R: Run \n”); printf (“What do you want to do? \n“); scanf (“%c”, &choice); switch (choice) { case ‘E’: printf (“Calling the Editor \n”); break; case ‘C’: printf (“Calling the Compiler \n”); break; case ‘R’: printf (“The program starts execution \n”); break; default: printf (“Invalid Input \n”); break; } // end switch return (0); } // end of main 1.Display the menu 2.Scanf choice 3.Switch for the value of choice: a.Case choice = ‘E’ printf (“Calling the Editor”) b.Break c.Case choice = ‘C’ printf (“Calling the Compiler”) d.Break e.Case choice = ‘R’ printf (“The program starts execution”) f.Break g.Otherwise printf (“Invalid input”); 4. End of program PSEUDOCODE Dr. Soha S. Zaghloul12
Sometimes, the same actions are to be performed on two different values. For example, capital and small letters in the previous example. The code will be then updated as follows: Dr. Soha S. Zaghloul13
#include int main (void) { char choice; printf (“Enter your choice \n”); printf (“E: Edit \n”); printf (“C: Compile \n”); printf (“R: Run \n”); printf (“What do you want to do? \n“); scanf (“%c”, &choice); switch (choice) { case ‘E’: case ‘e’: printf (“Calling the Editor \n”); break; case ‘C’: case ‘c’: printf (“Calling the Compiler \n”); break; case ‘R’: case ‘r’: printf (“The program starts execution \n”); break; default: printf (“Invalid Input \n”); break; } // end switch return (0); } // end of main Case choice = ‘E’ or ‘e’ printf (“Calling the Editor \n”) The default part is optional Dr. Soha S. Zaghloul14
Dr. Soha S. Zaghloul15
A string is a grouping of characters; i.e. words or phrases. We have already used strings constants extensively in printf and scanf statements. For example: printf (“Average = %f”, avg); The first argument “Average = %f” is a string constant. It consists of 12 characters. Note that the blanks are considered in the string length. Dr. Soha S. Zaghloul16
A string constant can be associated with #define. Example: #define INV_INPUT “Invalid Input Data” #define INSUFF_DATA “Insufficient Data” Dr. Soha S. Zaghloul17
Consider the following statement char string_var[30]; The previous statement declares a variable named string_var. Its type is char with length 30: i.e. a string consisting of 30 characters. Dr. Soha S. Zaghloul18
Consider the following statement char str[20] = “Initial Value”; The previous statement initializes a string variable named str. The value given is “ Initial Value ”. Let us look to str in memory after this declaration and initialization: Note that the first letter is positioned at 0 and the last one at position 19. Position 13, \0, read as the null character marks the end of the string. InitialValue\0?????? Dr. Soha S. Zaghloul19
The null character is counted within the string length. It gives to a string the flexibility to have a variable length. Therefore, the minimum size of str is 0. The maximum length is 20. All C’s string-handling functions simply ignore whatever is stored in the cells following the null character \0. InitialValue\0?????? Dr. Soha S. Zaghloul20
The null character is counted within the string length. It gives to a string the flexibility to have a variable length. Therefore, the minimum size of str is 0. The maximum length is 20. All C’s string-handling functions simply ignore whatever is stored in the cells following the null character \0. NUMBERSAND STRINGS\ Dr. Soha S. Zaghloul21
Use %s to handle string variables in printf. Example: printf (“Topics: %s \n”, str_var); The default of the output is “right-justified”. Placing a minus sign causes the output to be “left-justified”. A number before s specifies the number of coulumns in which the string is to be displayed. Example: char writer[20] = “Ahmad Ragab”; //11 chars printf (“Mr. %-20s \n”, writer); Outputs: Mr.~Ahmad~Ragab~~~~~~~~~ Dr. Soha S. Zaghloul22
Use %s to handle string variables in scanf. Do not put the & for strings in scanf. (This will be justified later when you study arrays). Dr. Soha S. Zaghloul23
#include #define STRING_LEN 10 int main (void) { char dept[STRING_LEN]; int course_num; char days[STRING_LEN]; int time; printf (“Enter department code, course number, “); printf (“days and time \n”); scanf (“%s%d%s%d”, dept, &course_num, days, &time); printf (“%s %d meets %s at %d\n”, dept, course_num, days, time); return (0); } // end of main function Dr. Soha S. Zaghloul24
Dr. Soha S. Zaghloul25 Enter department code, course number, days and time printf (“Enter department code, course number, “); printf (“days and time \n”); scanf (“%s%d%s%d”, dept, &course_num, days, &time); printf (“%s %d meets %s at %d\n”, dept, course_num, days, time); _ CSC CSC 201 meets 135 at 11 When entering strings data using scanf, a white space specifies the location of the null character. In other words, internal spaces are not allowed within strings entered through the scanf.
Apart from the string initialization, the assignment operator DOES not work with a string. Example: char string1[20] = “test string”; //this is correct char string1[20]; string1 = “test string”; //this is wrong C provides the string assignment operation through library functions. This is called string.h. Therefore, if your program uses C string library functions you should include string.h at the start: #include Dr. Soha S. Zaghloul26
strcpy copies the second argument into its first one. The faulty line in the previous slide should be written as: char string1[20]; strcpy (string1, “test string”); //this is correct Consider this example: char string1[20]; strcpy (string1, “a very long test string”); //overflow The result of the above example is unpredictable: It may overwrite other variables The system may generate a run-time error Dr. Soha S. Zaghloul27
Dr. Soha S. Zaghloul28 strncpy takes an extra argument to avoid the unpredictable error that may be caused by strcpy. The extra argument is n: the number of characters to copy. If the source string is longer than n characters, only the first n characters are copies. Example: This will copy only the first 20 characters of the string constant. Therefore, string1 will be as follows in the memory: char string1[20]; strncpy (string1, “a very long test string”, 20); a verylongteststr
Note that the stored string is invalid because it does not contain the null character /0. In order to avoid this, n should be equal to (destination length – 1), which is 19 in this example. Note that string1[19] = ‘\0’ char string1[20]; strncpy (string1, “a very long test string”, 19); a verylongteststr a verylongtestst \ Dr. Soha S. Zaghloul29
Dr. Soha S. Zaghloul30 Consider the following code segment: char result1[10], s1[15] = “Sep. 18, 2014”; strncpy (result1, s1, 9); Sep. 18, 2014 \0 ? s1 Sep. 18, \ result1 char result2[10], s1[15] = “Sep. 18, 2014”; strncpy (result2, &s1[5], 2) Copies 9 characters from s1 to result1 starting from s1[0] Copies 2 characters from s1 to result2 starting from s1[5] 18 \0 ?????? ? result2 strncpy (result1, &s1[0], 9);
Strings CANNOT be used as labels (cases) in a switch statement. The following code is WRONG because name is a string. char name[20]; printf (“Enter your first name: \n”); scanf (“%s”, name); switch (name) { case “Ahmad”: printf (“Ahmad is a nice boy \n”); break; case “Laila” : printf (“Laila is a nice girl \n”); break; } Dr. Soha S. Zaghloul31