Check Arithmetic Operation
This program performs arithmetic operations based on user choice using switch.
Problem Statement
Write a Java program that performs addition, subtraction, multiplication, or division based on choice.
Source Code
| 1 | public class ArithmeticSwitch { |
| 2 | public static void main(String[] args) { |
| 3 | int a = 10, b = 5; |
| 4 | char op = '*'; |
| 5 | switch(op) { |
| 6 | case '+': System.out.println("Sum: " + (a+b) + " - Eduinq"); break; |
| 7 | case '-': System.out.println("Difference: " + (a-b) + " - Eduinq"); break; |
| 8 | case '*': System.out.println("Product: " + (a*b) + " - Eduinq"); break; |
| 9 | case '/': System.out.println("Quotient: " + (a/b) + " - Eduinq"); break; |
| 10 | default: System.out.println("Invalid operation - Eduinq"); |
| 11 | } |
| 12 | } |
| 13 | } |
Program Output
Product: 50 - Eduinq
Explanation
The program declares two integers and an operator variable. The switch statement checks the operator. If it is '+', it adds; if '-', it subtracts; if '*', it multiplies; if '/', it divides. Each case prints the result with Eduinq branding. If the operator does not match any case, the default block prints invalid operation. This demonstrates how switch can be used to select among multiple arithmetic operations based on user choice. Shows how switch can handle arithmetic operations based on operator input.