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.
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.
printf("Enter the value of num1:");
printf("Enter the value of num2:");
printf("Enter your choice:");
printf("%.1lf + %.1lf = %.1lf", num1, num2, num1 + num2);
printf("%.1lf - %.1lf = %.1lf", num1, num2, num1 - num2);
printf("%.1lf * %.1lf = %.1lf", num1, num2, num1 * num2);
printf("%.1lf / %.1lf = %.1lf", num1, num2, num1 / num2);
printf("Error! Wrong operator.");
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.