Switch statement examples
/* Example for a switch statement */
/* Uses an integer value for choice. Note what happens if the breaks
are removed.
*/
#include <stdio.h>
int main(void)
{
int choice;
printf("\nEnter 1, 2, 3 . Enter a 4 to quit ");
scanf("%d", &choice);
switch(choice)
{
case 1: printf("\nyou entered one \n");
case 2: printf("\nyou entered two \n");
case 3: printf("\nyou entered three \n");
case 4: printf("\nyou asked to quit\n");
default: printf("\nyou entered an invalid number\n");
}
return (0);
}
OUTPUT from multiple runs of the program:
Enter 1, 2, 3 . Enter a 4 to quit 1
you entered one
you entered two
you entered three
you asked to quit
you entered an invalid number
Enter 1, 2, 3 . Enter a 4 to quit 3
you entered three
you asked to quit
you entered an invalid number
Enter 1, 2, 3 . Enter a 4 to quit 4
you asked to quit
you entered an invalid number
/* Example for a switch statement */
/* Uses an integer value for choice. Note what happens with the addition
of the breaks
*/
#include <stdio.h>
int main(void)
{
int choice;
printf("\nEnter 1, 2, 3 . Enter a 4 to quit ");
scanf("%d", &choice);
switch(choice)
{
case 1: printf("\nyou entered one \n"); break;
case 2: printf("\nyou entered two \n"); break;
case 3: printf("\nyou entered three \n"); break;
case 4: printf("\nyou asked to quit\n"); break;
default: printf("\nyou entered an invalid number\n");
}
return (0);
}
OUTPUT from multiple runs
Enter 1, 2, 3 . Enter a 4 to quit 1
you entered one
Enter 1, 2, 3 . Enter a 4 to quit 3
you entered three
Enter 1, 2, 3 . Enter a 4 to quit 4
you asked to quit
Enter 1, 2, 3 . Enter a 4 to quit 9
you entered an invalid number
/* Example for a switch statement */
/* Uses a char value for choice. Note how the breaks are used in this
example. Also note the readability of this example vs. that of the
previous ones.
*/
#include <stdio.h>
int main(void)
{
char choice;
printf("\nEnter a, b, c. Enter a q to quit ");
scanf(" %c", &choice);
switch(choice)
{
case 'A':
case 'a': printf("\nyou entered A\n");
break;
case 'B':
case 'b': printf("\nyou entered B\n");
break;
case 'C':
case 'c': printf("\nyou entered C\n");
break;
case 'Q':
case 'q': printf("\nyou asked to quit\n");
break;
default: printf("\nyou entered an invalid character\n");
}
return (0);
}