Error handling
Safely catch invalid inputs with try/catch.
Menu and loop
To make the calculator run continuously we need two constructs: a menu and a loop.
The menu calls the right method based on the operator the user picks. In C#, switch is a good fit for a menu: each case represents one operator. For continuous running we use a while loop; the loop keeps turning while the condition holds.
In this lesson we'll combine switch and while so the calculator can handle multiple operations.
The switch case construct
The switch statement takes an expression and branches to the matching case label. In the calculator we test the operator string ("+", "-", "*", "/") with switch.
switch (op)
{
case "+":
result = calc.Add(a, b);
break;
case "/":
result = calc.Divide(a, b);
break;
}Each case block must end with break; otherwise execution falls through to the next case.
Exercise Add the menu loop
Build a while loop over the ops array. Each iteration, take the operator, call the right method with switch, and print the result with Console.WriteLine(result). Add break after each case. Don't forget i++ at the end of the loop.
Show example solution
Inside the while loop, use switch to call the matching method for each operator.
Example solution:
using System;
class Calculator
{
public double Add(double a, double b) { return a + b; }
public double Subtract(double a, double b) { return a - b; }
public double Multiply(double a, double b) { return a * b; }
public double Divide(double a, double b)
{
if (b == 0) throw new DivideByZeroException("Division by zero");
return a / b;
}
}
class Program
{
static void Main()
{
var calc = new Calculator();
// Fixed operator list for testing
string[] ops = { "+", "-", "*", "/" };
double a = 20;
double b = 5;
int i = 0;
while (i < ops.Length)
{
string op = ops[i];
double result = 0;
switch (op)
{
case "+":
result = calc.Add(a, b);
break;
case "-":
result = calc.Subtract(a, b);
break;
case "*":
result = calc.Multiply(a, b);
break;
case "/":
result = calc.Divide(a, b);
break;
}
Console.WriteLine(result);
i++;
}
}
}
Test yourself
-
Match each operator to its operation
- +
- Addition
- -
- Subtraction
- *
- Multiplication
- /
- Division
-
Which loop is used for continuous running?
- for (fixed number of steps)
- if (a condition)
- try (error handling)
- while (as long as a condition holds)
Show answer
while (as long as a condition holds) — Correct; while runs the loop as long as the condition holds.
-
Write the while condition
int i = 0; while (____) { // loop body i++; }Show answer
int i = 0; while (i < ops.Length) { // loop body i++; }