Multiply and divide
Add multiplication, division and the divide-by-zero check.
The four arithmetic methods
Now that the skeleton class is in place, we can fill the methods with real arithmetic. C# has four basic operators:
+addition-subtraction*multiplication/division
Each method combines its two parameters with the operator and returns the result. For example, return a + b; is the body of the addition method. The Divide method will get an extra zero check.
Division by zero guard
In the Divide method we must check whether the divisor is zero. Division by zero is mathematically undefined and could crash the program.
C# reports this case with the DivideByZeroException exception. Inside the method we write if (b == 0) throw new DivideByZeroException(...); to throw the error explicitly. In the next lesson we'll catch this exception with try/catch.
Exercise Fill the four methods with arithmetic
Fill the four methods with real arithmetic. Add returns a + b, Subtract returns a - b, Multiply returns a * b. In Divide, first check b == 0; if so, throw new DivideByZeroException("Division by zero"), otherwise return a / b.
Show example solution
Write each return with the matching operator; add if (b == 0) throw new DivideByZeroException(...); inside Divide.
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)
{
// Check whether the divisor is zero
if (b == 0) throw new DivideByZeroException("Division by zero");
return a / b;
}
}
class Program
{
static void Main()
{
string input = "25";
double number = double.Parse(input);
var calc = new Calculator();
Console.WriteLine(calc.Add(number, 4));
}
}
Test yourself
-
Write the multiplication operator
public double Multiply(double a, double b) { return a ____ b; }Show answer
public double Multiply(double a, double b) { return a * b; } -
What should we do if the divisor is 0 in division?
- Return infinity
- Throw DivideByZeroException
- Set the result to 0
- Let the program crash
Show answer
Throw DivideByZeroException — Correct; division by zero should be thrown explicitly.
-
Match each method to its expression
- Add
- a + b
- Subtract
- a - b
- Multiply
- a * b
- Divide
- a / b