In this tutorial you will learn about the C Program to Perform Arithmetic Operations Using Switch and its application with practical example.
In this tutorial, we will learn to create a simple calculator program to perform arithmetic operations using C Switch Statement in C programming language.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- C Data Types
- C Variables
- C Input Output
- C Operators
- C Switch Case Statement
Program to Perform Arithmetic Operations Using Switch
In this program we will accept two operands and an arithmetic operator (+, -, *, /) from the user. Then, we will perform the calculation on the two operands based upon the operator entered by the user. Later in the program we will display the result based on operands and arithmetic operator provided.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <stdio.h> int main() { double num1,num2; char chr; printf("Enter the value of num1:"); scanf("%lf",&num1); printf("Enter the value of num2:"); scanf("%lf",&num2); printf("+.Addition \n"); printf("-.Subtraction \n"); printf("*.Multiplication \n"); printf("/.Division \n"); printf("Enter your choice:"); scanf(" %c",&chr); switch(chr){ case '+': printf("%.1lf + %.1lf = %.1lf", num1, num2, num1 + num2); break; case '-': printf("%.1lf - %.1lf = %.1lf", num1, num2, num1 - num2); break; case '*': printf("%.1lf * %.1lf = %.1lf", num1, num2, num1 * num2); break; case '/': printf("%.1lf / %.1lf = %.1lf", num1, num2, num1 / num2); break; default: printf("Error! Wrong operator."); } return 0; } |
Output:-
In the above program, we have first declared and initialized a set variables required in the program.
- num1 = it holds the first number value
- num2 = it holds the second number value
- chr = it holds the operator choice
In the next statement user will be prompted to enter the two number values which will be assigned to variable ‘num1’ and ‘num2’ respectively. Next, we will display operator menu and ask user to input operator (+, -, *, /) choice. When user enter operator, it will be assigned to ‘chr’ variable. Then, depending on the value of ‘chr’ switch statement we will perform the calculation on the two operands. Finally, this will be displaying the result using printf statement.