You are here:   HomeC Programming (Theory)Control Structures in CWrite a C program to a simple 4 function calculator.
by Dinesh Thakur Category: Control Structures

 

 

#include<stdio.h>

#include<conio.h>
void main()
{
char line[100];
int result =0;
char operator;
int value;
while(1)
{
printf("Result:%d\n",result);
printf("Enter operator and number:");
fgets(line,sizeof(line),stdin);
sscanf(line,"%C %d",&operator,&value);
if((operator == 'q')||(operator == 'Q'))
break;
switch(operator)
{
case '+':
result += value;
break;
case '-':
result -= value;
break;
case '*':
result *= value;
break;
case '/':
if(value == 0)
{
printf("Error:Divide by zero\n");
printf("operation ignored\n");
}
else
result /= value;
break;
default:
printf("Unknown operator %c\n",operator);
break;
}
}
getch();
}
 
OUTPUT:
Result: 0
Enter operator and number: + 15
Result: 15
Enter operator and number: - 5
Result: 10
Enter operator and number: Q


Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular





Popular Article