GE6151 Computer Programming SWITCH CASE:

SWITCH CASE:

The switch case statement is a better way of writing a program when a series of if elses occurs. The general format for this is,

switch(expression)

{

case value1: Program statement; program statement; break;

case valuen: program statement; break;

default:

break;

}

The keyword break must be included at the end of each case statement. The default clause is optional, and isexecuted if the cases are not met. The right brace at the end signifies the end of the case selections.

Example:

#include <stdio.h>

main()

{

int menu, numb1, numb2, total; printf("enter in two numbers -->"); scanf("%d %d", &numb1, &numb2 ); printf("enter in choice\n"); printf("1=addition\n"); printf("2=subtraction\n");

scanf("%d",&menu);

switch( menu )

{

case 1: total = numb1 + numb2; break;

case 2: total = numb1 - numb2; break;

default:printf("Invalidoptionselected\n");

}

if( menu == 1 )

printf("%d plus %d is %d\n", numb1, numb2, total ); else if( menu == 2 )

printf("%d minus %d is %d\n", numb1, numb2, total );

}

The above program uses a switch statement to validate and select upon the users input choice, simulating a simple menu of choices.