Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
2K views

C Program To Make A Simple Calculator

This C program allows a user to enter an arithmetic operator and two operands. It uses a switch statement to perform the appropriate calculation (+, -, *, /) on the operands based on the operator entered by the user. The program takes the operator and operand values as input, performs the calculation in the switch statement, and prints out the result.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
2K views

C Program To Make A Simple Calculator

This C program allows a user to enter an arithmetic operator and two operands. It uses a switch statement to perform the appropriate calculation (+, -, *, /) on the operands based on the operator entered by the user. The program takes the operator and operand values as input, performs the calculation in the switch statement, and prints out the result.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

C Program to Make a Simple Calculator

This program takes an arithmetic operator +, -, *, / and two operands from the user
and performs the calculation on the two operands depending upon the operator
entered by the user.

Example: Simple Calculator using switch Statement

// Performs addition, subtraction, multiplication or division depending the input from


user

# include <stdio.h>

int main() {

char operator;
double firstNumber,secondNumber;

printf("Enter an operator (+, -, *,): ");


scanf("%c", &operator);

printf("Enter two operands: ");


scanf("%lf %lf",&firstNumber, &secondNumber);

switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber, firstNumber +
secondNumber);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber -
secondNumber);
break;

case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber *
secondNumber);
break;

case '/':
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber /
secondNumber);
break;

// operator doesn't match any case constant (+, -, *, /)


default:
printf("Error! operator is not correct");
}

return 0;
}

Output

Enter an operator (+, -, *,): *

Enter two operands: 1.5

4.5

1.5 * 4.5 = 6.8


The * operator entered by the user is stored in the operator variable and the two
operands, 1.5 and 4.5 are stored in variables firstNumber and secondNumber
respectively.

Since, the operator * matches the case case '*':, the control of the program jumps to

printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber * secondNumber);

This statement calculates the product and displays it on the screen.

Finally, the break; statement ends the switch statement.

You might also like