Dr. A.P.J. Abdul Kalam Technical University, Lucknow
KCS101 / KCS201 Programming for Problem Solving - Using C Language
Lab Exercises
11. Write a program that takes two operands and one operator from the user and perform the operation and prints the result by using Switch statement.
/*
File: Prgrm11.c
Author: Aditya Saini
Date: Sept 30, 2019
Description: Program to simulate a calculator using Switch statement.
*/
#include <stdio.h>
int main (void)
{
int operand_1, operand_2;
char operator;
int result;
//Input operands and operator.
printf ("Input first operand: ");
scanf ("%d", &operand_1);
char operator;
int result;
//Input operands and operator.
printf ("Input first operand: ");
scanf ("%d", &operand_1);
printf ("Input second operand: ");
scanf ("%d", &operand_2);
printf ("Input operator: ");
fflush (stdin);
scanf ("%c", &operator);
//Finding the result using Switch statement.
switch (operator)
{
case '+':
result = operand_1 + operand_2;
break;
case '-':
result = operand_1 - operand_2;
break;
case '*':
result = operand_1 * operand_2;
break;
case '/':
result = operand_1 / operand_2;
break;
default:
printf ("Error! Wrong Operator.");
return 0;
}
//Output the result
printf ("%d %c %d = %d", operand_1, operator, operand_2, result);
{
case '+':
result = operand_1 + operand_2;
break;
case '-':
result = operand_1 - operand_2;
break;
case '*':
result = operand_1 * operand_2;
break;
case '/':
result = operand_1 / operand_2;
break;
default:
printf ("Error! Wrong Operator.");
return 0;
}
//Output the result
printf ("%d %c %d = %d", operand_1, operator, operand_2, result);
};
Output
Input first operand: 20
Input second operand: 25
Input operator: +
20 + 25 = 45Input second operand: 25
Input operator: +
No comments:
Post a Comment
Please do not post spam links.