Write a C program to Make Simple calculator.
Write a program and call it calculator.c which is the basic calculator and receives three values from input via keyboard.
- The first value as an operator (Op1) should be a char type and one of (+, -, *, /, s) characters with the following meanings:1 ‘+’ for addition (num1 + num2)
2 ‘-’ for subtraction (num1 – num2)
3 ‘*’ for multiplication (num1 * num2)
4 ‘/’ for division (num1 / num2) - Program should receive another two operands (Num1, Num2) which could be float or integer.
- The program should apply the first given operator (Op1) into the operands (Num1, Num2) and prints the relevant results with related messages in the screen.
/**
C Program to Make a Simple Calculator Using switch case by codebind.com
*/
# include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
float num1, num2, result;
char choice, opcode;
bool bCont = true; // flag to denote good input
while(1)
{
puts("Enter a choice from the list below\n\n");
puts("1 Addition\n");
puts("2 Subtraction\n");
puts("3 Multiplication\n");
puts("4 Division\n\n");
puts("q Quit\n\n");
do
{
bCont = true;
puts("Enter choice: "); //User input for the calculator menu
scanf("%c", &choice);
if(choice == 'q')
{
exit(0);
}
if((choice < '1') || (choice > '4'))
{
puts("enter 1 - 4 or q, please try again");
bCont = false;
}
} while (!bCont);
printf("Enter first number: "); //User input for first number
scanf("%f", &num1);
printf("Enter second number: "); //User input for second number
scanf("%f", &num2);
switch(choice) //switch statement for menu
{
case '1':
result = num1 + num2; //Addition calculation
opcode = '+';
break;
case '2':
result = num1 - num2; //Addition calculation
opcode = '-';
break;
case '3':
result = num1 * num2; //Addition calculation
opcode = '*';
break;
case '4':
if(0 != num2)
result = num1 / num2; //Addition calculation
opcode = '/';
break;
} // end of switch
printf("%.2f %c %.2f = %.2f\n", num1, opcode, num2, result);
} // end of infinite while loop
}
/*
OUTPUT
Enter a choice from the list below
1 Addition
2 Subtraction
3 Multiplication
4 Division
q Quit
Enter choice:
1
Enter first number: 66
Enter second number: 55
66.00 + 55.00 = 121.00
Enter a choice from the list below
1 Addition
2 Subtraction
3 Multiplication
4 Division
q Quit
Enter choice:
enter 1 - 4 or q, please try again
Enter choice:
*/
Leave a Reply