UncleCoder.com

UncleCoder.com

Free programming examples and instructions

C program to perform simple calculator operations using switch case

C program for study switch case and code for simple calculator using switch case

by Krishna viswambharan


Posted on 25 Aug 2017 Category: C Views: 758

Edited on 27 Aug 2017


C program to perform simple calculator operations using switch case 

When we want to solve a multiple option type programs such as menu driven programs , for example ,calculator programs, we can use switch statement .In this type, we can choose only one case at a time. If the choice matches with any of the cases , that particular block of code will execute and if there is no matches, then the default case will execute. ‘break’ statements are used in each block because they helps the program flow to come out of the switch body after the execution of that case. Otherwise all cases after the correct statement will execute.

The syntax of switch-case statement is given as follows:-

switch(expression) 
{
   case constant:
      		statement(s);
      		break;	
   case constant:
      		statement(s);
      		break;
  
   /* we can have n number of case statements */
   default :  
  	 statement(s);
}

The following is an example for switch case statement

#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
	int num1,num2,sum=0,diff=0,prod=0,ch;
	float result=0;
	while(1)
	{
		printf("\t\tMENU\t\t\n");
		
		printf("1.ADDITION\n");
		printf("2.SUBTRACTION\n");
		printf("3.MULTIPLICATION\n");
		printf("4.DIVISION\n");
		printf("5.EXIT\n");
		
		printf("Enter your choice :");
		scanf("%d",&ch);
		switch(ch)
		{
		case 1:
			printf("Enter the first number :");
			scanf("%d",&num1);
            printf("Enter the second number :");
			scanf("%d",&num2);
			sum=num1+num2;
			printf("Sum= %d",sum);
			break;
		case 2:
			printf("Enter the first number :");
			scanf("%d",&num1);
            printf("Enter the second number :");
			scanf("%d",&num2);
			diff=num1-num2;
			printf("The difference is %d",diff);
			break;
		case 3:
			printf("Enter the first number :");
			scanf("%d",&num1);
            printf("Enter the second number :");
			scanf("%d",&num2);			
            prod=num1*num2;
			printf("The product is %d",prod);
			break;
		case 4:
			printf("Enter the first number :");
			scanf("%d",&num1);
            printf("Enter the second number :");
			scanf("%d",&num2);							     
            result=(float)num1/num2;
			printf("The result is %f",result);
			break;
		case 5:
			exit(0);
		default:
			printf("Invalid input");
		}
		getch();
	}
}

output



Leave a Comment:


Advertisement