Enumerations and Beers - Lone Leth Thomsen

Solution index                   Textual C program


#include <stdio.h>
#include <stdlib.h>

int main(void){
   enum beer {tub = 1, carls, slots} mybeer;

   printf("\nChoose a number between 1 and 3: ");
   scanf("%d", &mybeer);

   switch (mybeer){
       case tub: 
         printf("\nTuborg\n"); 
         break;
       case carls: 
         printf("\nCarlsberg\n"); 
         break;
       case slots: 
         printf("\nSlots Pilsner\n"); 
         break;
       default:
         printf("\nYou don't like beer\n");
   }

   system("PAUSE");	
   return 0;
}


Summary of exercise: Write a simple program that defines three different types of beer (hint: use an enumerator). Create a variable myfavoitebeer of the just created enumerator type and let the user choose his favorite beer (among one of the three). Print the real/full name of the user's favorite beer.
 

   enum beer {tub = 1, carls, slots} mybeer;
An enumerator with 3 identifiers (tub, carls and slots) are defined. The identifiers are numbered from 1 and up. A variable called mybeer of type beer is defined.
 

   printf("\nChoose a number between 1 and 3: ");
   scanf("%d", &mybeer);
Read an int value into the mybeer variable (which only can be assigned integer values).
 

   switch (mybeer){
       case tub: 
         printf("\nTuborg\n"); 
         break;
       case carls: 
         printf("\nCarlsberg\n"); 
         break;
       case slots: 
         printf("\nSlots Pilsner\n"); 
         break;
       default:
         printf("\nYou don't like beer\n");
   }
Remember that a switch can be used kind of like an if-then-else statement, however a switch can only be used on int values (which the enumerator identifiers also are). If mybeer has the int value 1, which is the same as the enumerator identifier tub, then print Tuborg. Similar if mybeer has the int value 2, which is the same as the enumerator identifier carls, then print Carlsberg. Guess what happens if mybeer has the int value 3... :) With a switch statement, you can define a default statement that is executed if the switch variable (mybeer) isn't either 1, 2, or 3.
 


Generated: Wednesday, March 29, 2006, 12:33:35
This program dissection page is generated from an XML-in-LAML source file