Let’s see an example of the switch statement in action. This program imitates a lottery with three winning numbers. Users guess a number, and if the number is correct then they win a prize.
#include <stdio.h> int main(void){ int choice = 0; printf("Pick a number between 1 and 100 and you might win a prize!\n"); //get input scanf(" %d", &choice); //validate input if((choice > 100) || (choice<1)){ printf("Choice was invalid. Sorry!\n"); //return 1 to OS return 1; } switch(choice){ case 42: printf("\nCongratulations! You win a towel.\n"); break; case 43: printf("\nCongratulations! You win a hacky-sack.\n"); break; case 73: printf("\nCongratulations! You win a Flash comic book.\n"); break; default: printf("You won absolutely nothing! You guessed wrong.\n"); break; } return 0; }
We store the user’s guess in the choice variable. Before we process the user’s choice, we make sure that the choice is within the parameters we gave. If it isn’t, we inform the user and return control to the operating system.
To process the user’s input, we use a switch statement. If the user does not guess one of the three right numbers, the default message is printed informing the user that they have lost.
Not every switch option needs to end with a break. Sometimes it is valuable to allow the execution to “fall through” to the next option. Let’s see an example of this.
#include <stdio.h> int main(void){ char response = 'x'; printf("Do you agree (y/n):\t"); scanf(" %c", &response); switch(response){ case 'y': case 'Y': printf("You said yes!"); break; case 'n': case 'N': printf("You said no!"); break; default: printf("You said... I dunno what you said."); break; } return 0; }
If you want to see more fun stuff, take a look at my author page: http://www.amazon.com/Al-Jensen/e/B008MN382O/