C — Functions, parameters, and return values
A C function receives each integer parameter by value. The caller can use the returned integer in another calculation without printing it first.
A simple example
Call a function with 2
- Start with Argument 2
- Do this Double the argument
- Result 4
#include <stdio.h>
int twice(int n) {
return n + n;
}
int main(void) {
printf("%d\n", twice(2));
}
4
Calculate how many boxes an order needs
The parameter names exist only inside boxes_needed. The caller passes integer values. Comparing the remainder with zero produces either 0 or 1, which supplies the extra box.
A library ships 17 books in cartons that hold eight. Two cartons take sixteen books, leaving one book that still needs a carton. An order of exactly sixteen needs only two.
Run the example
C17. Run these commands from the directory containing the example. Use a Unix-style shell.
cc -std=c17 lesson.c -o lesson
./lesson
#include <stdio.h>
int boxes_needed(int items, int capacity) {
return items / capacity + (items % capacity != 0);
}
int main(void) {
printf("%d\n", boxes_needed(17, 8));
printf("%d\n", boxes_needed(16, 8));
return 0;
}
3 2
The input contract is a nonnegative whole-number item count and a positive box capacity. Seventeen items fill two boxes of eight with one item left over. Sixteen items fill exactly two boxes.
Try it yourself
How many boxes do zero items need?
Check your answer
Zero. The quotient and remainder are both zero. A zero capacity is outside the function’s contract because division by zero is undefined.