switch adalah sebuah statement yang digunakan untuk menentukan perintah untuk beberapa kasus tertentu. Dalam contoh dibawah ini,
printf( "Enter the EOF character to end input.\n" );
switch ( grade ) { /* switch nested in while */
case 'A': /* grade was uppercase A */
case 'a': /* or lowercase a */
++aCount; /* increment aCount */
break; /* necessary to exit switch */
case 'B': /* grade was uppercase B */
case 'b': /* or lowercase b */
++bCount;
break; /* necessary to exit switch */
case 'C': /* grade was uppercase C */
case 'c': /* or lowercase c */
++cCount; /* increment cCount */
break; /* necessary to exit switch */
case 'D': /* grade was uppercase D */
case 'd': /* or lowercase d */
++dCount; /* increment dCount */
break; /* necessary to exit switch */
case 'F': /* grade was uppercase F */
case 'f': /* or lowercase f */
++fCount; /* increment fCount */
break; /* necessary to exit switch */
case '\n': /* ignore newlines, */
case '\t': /* tabs, */
case ' ': /* and spaces in input */
break; /* necessary to exit switch */
default: /* catch all other characters */
printf( "Incorrect letter grade entered." );
printf( " Enter a new grade.\n" );
break; /* optional; will exit switch anyway */
printf( "Enter the EOF character to end input.\n" );
switch ( grade ) { /* switch nested in while */
case 'A': /* grade was uppercase A */
case 'a': /* or lowercase a */
++aCount; /* increment aCount */
break; /* necessary to exit switch */
case 'B': /* grade was uppercase B */
case 'b': /* or lowercase b */
++bCount;
break; /* necessary to exit switch */
case 'C': /* grade was uppercase C */
case 'c': /* or lowercase c */
++cCount; /* increment cCount */
break; /* necessary to exit switch */
case 'D': /* grade was uppercase D */
case 'd': /* or lowercase d */
++dCount; /* increment dCount */
break; /* necessary to exit switch */
case 'F': /* grade was uppercase F */
case 'f': /* or lowercase f */
++fCount; /* increment fCount */
break; /* necessary to exit switch */
case '\n': /* ignore newlines, */
case '\t': /* tabs, */
case ' ': /* and spaces in input */
break; /* necessary to exit switch */
default: /* catch all other characters */
printf( "Incorrect letter grade entered." );
printf( " Enter a new grade.\n" );
break; /* optional; will exit switch anyway */
Pada program diatas, jika user menginputkan nilai ‘A’ atau ‘a’, maka nilai dari variable aCount akan ditambahkan satu, begitu juga untuk B,b,C,c,D,d,F,f, dst. Perintah “break” menandakan bahwa pernyataan switch akan berhenti dan tidak akan mengecek case-case lain dibawahnya. Semantara untuk default, ini merupakan opsional.
0 komentar:
Posting Komentar