C Program to Make a Simple Calculator Using switch...case - My CS Tutorial - My CS Tutorial

Breaking

Programming languages full tutorial and programs, exam papers, visual basic( Vb.net ), information of new technologies and more....

Sunday, November 17, 2019

C Program to Make a Simple Calculator Using switch...case - My CS Tutorial

In this tutorial,we will learn how write a program that solve +,-,*,/ operations.In this post we will make a calculator that solve arithmetic operations.This is a C program to create a simple calculator using switch and break statement.


Explanation:-


The program starts with initializing

choice → For storing the operators as +,-,/,*

num1,num2 → For storing two integers

result → For storing the resulting value

flag → To store true or false.

First we take choice of user (+,-,/,*) then the two numbers.

Now we use switch case

If the user enters '+' as his choice then the result will be result=num1+num2

If the user enters '-' as his choice then the result will be result=num1-num2

If the user enters '/' as his choice then the result will be result=num1/num2

if num2 is not zero else flag will be zero and the output would be undefined

If the user enters '*' as his choice then the result will be result=num1*num2



C program code



#include<stdio.h>
#include<conio.h>
void main()
{
char choice;
float num1,num2,result;
int flag=1;
printf("\n Enter +,-,/,* for knowing the result: ");
scanf("%c",&choice);
printf("\n Enter first number: ");
scanf("%f",&num1);
printf("\n Enter second number: ");
scanf("%f",&num2);

switch(choice)
{
case '+':
result=num1+num2;
break;
case '-':
result=num1-num2;
break;
case '/':
{

if(num2==0)
{
flag=0;
}
else
{
result=num1/num2;
}
break;
}
case '*': result=num1*num2;
break;
default:printf("Error");
break;
}
if(flag==1)
{
printf("\n %f %c %f = %f",num1,choice,num2,result);
}
else
{
printf("%f %c %f = undefined\n",num1,choice,num2);
}
getch();
}



OUTPUT 1:




OUTPUT 2:







In first output,the operation is ( + ) and the value of input first and second number is 45 and 50
After operation
The value is 95

45 + 50 = 95

In second output,the operation is ( / ) and the value of input first and second number is 55 and 10
After operation
The value is 5.5

55 / 10 =5.5



Please share this post and blog link with your friends.For more programs use this blog.
If you have any problem, please comment in comment box, subscribe this blog for notifications of new post on your email and follow this blog.

Created by-- HARSH CHAUHAN

1 comment: