Add and subtract
- C course
- Beginner
- Lesson 20/116
- 6 min
Add and test the addition and subtraction functions.
The add and subtract functions
The first functions of the calculator are add and subtract. Both take two ints and return an int:
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}We call these from main as add(5, 3); the result is 8. subtract(5, 3) gives 2.
Practice Add add and subtract
Add int add(int a, int b) and int subtract(int a, int b) functions to the skeleton below. Call both in main: printf("%d\n", add(5, 3)); and printf("%d", subtract(5, 3));. Keep the existing printf.
Starter code
#include <stdio.h>
int main(void) {
printf("Calculator");
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 main(void) {
printf("Calculator\n");
printf("%d\n", add(5, 3));
printf("%d", subtract(5, 3));
return 0;
}Expected output
Calculator 8 2
Calling functions from main
After defining functions, you can call them from main. A call is the function name followed by arguments in parentheses:
int result = add(5, 3);
printf("%d", result);Or use them directly inside printf: printf("%d", add(5, 3));. This is shorter and needs no intermediate variable.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does add(5, 3) return?
int add(int a, int b) {
return a + b;
}- 8 Correct answer
- 53
- 2
- 15
Explanation: The add function returns a + b.
2 Complete the return statement
int add(int a, int b) { return a ____ b; }
int add(int a, int b) { return a + b; }
Explanation: return a + b; performs addition.
3 Match the operators
| Term | Meaning |
|---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |