Program to Make a Simple Calculator Using switch...case - (C# Basic Programs)
Making a simple calculator is a common programming exercise that helps improve the problem-solving skills of programmers. In this tutorial, we will discuss a program to make a basic calculator using switch...case in C# programming language.
Syntax
The syntax for making a basic calculator using switch...case in C# programming language is as follows:
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
default:
Console.WriteLine("Invalid operator!");
break;
}
Example
using System;
namespace SimpleCalculator
{
class Program
{
static void Main(string[] args)
{
double num1, num2, result = 0;
char op;
Console.Write("Enter first number: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter operator (+, -, *, /): ");
op = Convert.ToChar(Console.ReadLine());
Console.Write("Enter second number: ");
num2 = Convert.ToDouble(Console.ReadLine());
switch (op)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
Console.WriteLine("Invalid operator!");
break;
}
Console.WriteLine(num1 + " " + op + " " + num2 + " = " + result);
Console.ReadKey();
}
}
}
Output:
Enter first number: 10
Enter operator (+, -, *, /): *
Enter second number: 5
10 * 5 = 50
Explanation
This program reads two numbers and an operator from the user and performs the corresponding calculation using switch...case statement. It takes the operator entered by the user and performs the corresponding arithmetic operation, and then displays the result.
Use
This program is great for practicing problem-solving skills and improving coding abilities. Simple calculator programs help programmers in developing a better understanding of switch...case statements, conditional statements, and how to manipulate variables to perform arithmetic operations.
Summary
In this tutorial, we discussed a program to make a basic calculator using switch...case in C# programming language. We have seen the syntax, example, explanation, and use of making a basic calculator in C#. By practicing these exercises, programmers can improve their problem-solving skills and become better equipped to tackle complex coding challenges.