Multiply and divide
- C course
- Beginner
- Lesson 21/116
- 6 min
Add multiplication, division and the divide-by-zero check.
The multiply and divide functions
Now we add multiply and divide functions. multiply multiplies two numbers; divide divides them. For division we must check b == 0 to prevent a divide-by-zero error:
int multiply(int a, int b) {
return a * b;
}
int divide(int a, int b) {
if (b == 0) return 0;
return a / b;
}Division by zero is undefined; the check prevents a crash.
Practice Add multiply and divide
Add int multiply(int a, int b) and int divide(int a, int b) functions to the code below. Inside divide, include if (b == 0) return 0;. Call both in main: printf("%d\n", multiply(5, 3)); and printf("%d", divide(6, 3));.
Starter code
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int main(void) {
printf("Calculator\n");
printf("%d\n", add(5, 3));
printf("%d", subtract(5, 3));
return 0;
}Sample solution
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
int divide(int a, int b) {
if (b == 0) return 0;
return a / b;
}
int main(void) {
printf("Calculator\n");
printf("%d\n", add(5, 3));
printf("%d\n", subtract(5, 3));
printf("%d\n", multiply(5, 3));
printf("%d", divide(6, 3));
return 0;
}Expected output
Calculator 8 2 15 2
The divide-by-zero danger
Division by zero causes the program to crash immediately. So we must check the divisor in the divide function:
if (b == 0) return 0; // safe returnYou can return a different value instead of zero; what matters is that the program does not crash. Production code usually uses an error code or a special value.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 multiply return statement
int multiply(int a, int b) { return a ____ b; }
int multiply(int a, int b) { return a * b; }
Explanation: return a * b; performs multiplication.
2 What should be checked before division?
- a > 0
- b == 0 Correct answer
- b > 0
- a < 0
Explanation: The b == 0 check prevents a divide-by-zero error.
3 Match the functions
| Term | Meaning |
|---|---|
add |
Addition |
subtract |
Subtraction |
multiply |
Multiplication |
divide |
Division |