C Programming

THE switch case STATEMENT

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


	/* Illustates nested if else and multiple arguments to the scanf function.  */
	#include <stdio.h>

	main()
	{
		int  invalid_operator = 0;
		char  operator;
		float  number1, number2, result;

		printf("Enter two numbers and an operator in the format\n");
		printf(" number1 operator number2\n");
		scanf("%f %c %f", &number1, &operator, &number2);

		if(operator == '*')
			result = number1 * number2;
		else if(operator == '/')
			result = number1 / number2;
		else if(operator == '+')
			result = number1 + number2;
		else if(operator == '-')
			result = number1 - number2;
		else
			invalid_operator = 1;

		if( invalid_operator != 1 )
			printf("%f %c %f is %f\n", number1, operator, number2, result );
		else
			printf("Invalid operator.\n");
	}

Solution


	/* Illustates switch */
	#include <stdio.h>

	main()
	{
		int  invalid_operator = 0;
		char  operator;
		float  number1, number2, result;

		printf("Enter two numbers and an operator in the format\n");
		printf(" number1 operator number2\n");
		scanf("%f %c %f", &number1, &operator, &number2);

		switch( operator ) {
			case '*' : result = number1 * number2; break;
			case '/' : result = number1 / number2; break;
			case '+' : result = number1 + number2; break;
			case '-' : result = number1 - number2; break;
			default : invalid_operator = 1;
		}
		switch( invalid_operator ) {
			case 1 : printf("Invalid operator.\n"); break;
			default : printf("%f %c %f is %f\n", number1, operator, number2, result );
		}
	}

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