C Programming

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 is executed if the cases are not met. The right brace at the end signifies the end of the case selections.


Rules for switch statements

	values for 'case' must be integer or character constants
	the order of the 'case' statements is unimportant
	the default clause may occur first (convention places it last)
	you cannot use expressions or ranges



	#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("Invalid option selected\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 );
	}


	Sample Program Output
	enter in two numbers --> 37 23
	enter in choice
	1=addition
	2=subtraction
	2
	37 minus 23 is 14

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


EXERCISE C11
Rewrite the previous program, which accepted two numbers and an operator, using the switch case statement.

Answer


©Copyright B Brown. 1984-1999. All rights reserved.