The switch Statement.  Occasionally, an algorithm will contain a series of decisions in which a variable or expression is tested separately for each.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Dynamic memory allocation
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Introduction to C Programming
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
C. About the Crash Course Cover sufficient C for simple programs: variables and statements control functions arrays and strings pointers Slides and captured.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
7. C program structure.
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
Introduction to C Programming
C How to Program, 6/e Summary © by Pearson Education, Inc. All Rights Reserved.
- SEARCHING - SORTING.  Given:  The array  The search target: the array element value we are looking for  Algorithm:  Start with the initial array.
 2007 Pearson Education, Inc. All rights reserved C Characters and Strings.
Input/Output  Input/Output operations are performed using input/output functions  Common input/output functions are provided as part of C’s standard.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
Chapter 2 Overview of C Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Flow of Control Part 1: Selection
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Nested LOOPS.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
30/10/ Iteration Loops Do While (condition is true) … Loop.
The switch Statement.  Occasionally, an algorithm will contain a series of decisions in which a variable or expression is tested separately for each.
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
Dr. Soha S. Zaghloul2 Let arr be an array of 20 integers. Write a complete program that first fills the array with up to 20 input values. Then, the program.
(9-1) Strings I H&K Chapter 8 Instructor - Andrew S. O’Fallon CptS 121 (October 19, 2015) Washington State University.
C++ Programming Lecture 7 Control Structure I (Selection) – Part II The Hashemite University Computer Engineering Department.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Constants, Variables and Data types in C The C character Set A character denotes any alphabet, digit or special symbol used to represent information.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
C++ Programming Lecture 19 Strings The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
 CSC111 Quick Revision. Problem Write a java code that read a string, then show a list of options to the user to select from them, where:  L to print.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
A.Abhari CPS1251 Topic 2: C Overview C Language Elements Variable Declaration and Data Types Statement Execution C Program Layout Formatting Output Interactive.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
 2003 Prentice Hall, Inc. All rights reserved. 1 Basic C++ Programming.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Chapter Nine Strings. Char vs String Literals Size of data types: Size of data types: –sizeof(“hello\n”)7 bytes –sizeof(“hello”)6 bytes –sizeof(“X”)2.
Chapter 4 Select … Case Multiple-Selection Statement & Logical Operators 1 © by Pearson Education, Inc. All Rights Reserved. -Edited By Maysoon.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Decision making If.. else statement.
The if…else Selection Statement
Strings CSCI 112: Programming in C.
Chapter 4 C Program Control Part I
Conditionals & Boolean Expressions
Arrays in C.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Control Statement Examples
Chapter 2 - Introduction to C Programming
INPUT & OUTPUT scanf & printf.
Functions.
1) C program development 2) Selection structure
Decision making If statement.
Strings Dr. Soha S. Zaghloul updated by Rasha ALEidan
Functions Extra Examples.
Variables in C Topics Naming Variables Declaring Variables
Introduction to C Programming
Presentation transcript:

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