A program to create a simple calculator using switch case:
Code:
#include <stdio.h>
#include <conio.h>
main()
{
clrscr();
char o;
int a,b;
printf("Enter two operators: ");
scanf("%d %d",&a,&b);
printf("Enter the operand(+,-,*,/): ");
scanf("%c",&o);
switch(o)
{
case '+':
printf("The addition of %d + %d = %d",a,b,a+b);
break;
case '-':
printf("The subtracation of %d - %d = %d",a,b,a-b);
break;
case '-':
printf("The multiplication of %d * %d = %d",a,b,a*b);
break;
case '-':
printf("The division of %d / %d = %d",a,b,a/b);
break;
default:
printf("Please enter a correct operator");
break;
}
getch();
}
In this way the output is somewhat like this:
Code:
Enter two operators : 8 3
Select an operator(*,-,*,/) Please enter a correct operator.
While in the program if i ask for to enter the operand first, then the output is working properly!
Code:
#include <stdio.h>
#include <conio.h>
main()
{
clrscr();
char o;
int a,b;
printf("Enter the operand(+,-,*,/): ");
scanf("%c",&o);
printf("Enter two operators: ");
scanf("%d %d",&a,&b);
switch(o)
{
case '+':
printf("The addition of %d + %d = %d",a,b,a+b);
break;
case '-':
printf("The subtracation of %d - %d = %d",a,b,a-b);
break;
case '-':
printf("The multiplication of %d * %d = %d",a,b,a*b);
break;
case '-':
printf("The division of %d / %d = %d",a,b,a/b);
break;
default:
printf("Please enter a correct operator");
break;
}
getch();
}
Output:
Code:
Select an operator(+,-,*,/) +
Enter two operands 4
5
The addition of 4 + 5 = 9
Just confused as logically according to my believe i think both are same right? i can ask to enter the operators first followed by the operand or the opposite! But in the first program the output is messed up as it is directly jumping outside showing that an invalid operand has been used.! :/