English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of C Programming Examples
In this example, you will learn to create a simple calculator using the switch statement in C programming language.
To understand this example, you should understand the followingC programming languageTopic:
This program requires an arithmetic operator+, -, *, /and two operands. Then, it performs the calculation on the two operands based on the operator entered by the user.
#include <stdio.h> int main() { char operator; double first, second; printf("Input operator (+, -, *,): "); scanf("%c", &operator); printf("Input two operands: "); scanf("%lf %lf", &first, &second); switch (operator) { case '+': printf("%.1lf + %.1lf = %.1lf", first, second, first + second); break; case '-': printf("%.1lf - %.1lf = %.1lf", first, second, first - second); break; case '*': printf("%.1lf * %.1lf = %.1lf", first, second, first * second); break; case '/': printf("%.1lf / %.1lf = %.1lf", first, second, first / second); break; //The operator does not match any case default: printf("Error! Operator is incorrect"); } return 0; }
Output result
Input operator(+, -, *,): * Input two operands: 1.5 4.5 1.5 * 4.5 = 6.8
user input*the operator is stored in operator. Moreover, two operands1.5and4.5stored separately in first and second.
Due to the operator*With case '*' : matches, so the program's control jumps to
printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
This statement calculates the result and displays it on the screen.
Finally, the break; statement ends the switch statement.