Writing functions
Read · 1 of 5
A function is a named recipe
int square(int x) { return x * x; } takes an int called x and gives back (returns) an int. square(7) runs it with x = 7 and becomes 49.
Functions go above main, so C has seen them before they're used. A function that returns nothing has the type void.
Read this lesson as text
Define a function once, call it as often as you like.
A function is a named recipe
int square(int x) { return x * x; } takes an int called x and gives back (returns) an int. square(7) runs it with x = 7 and becomes 49.
Functions go above main, so C has seen them before they're used. A function that returns nothing has the type void.
A call jumps in and comes back
#include <stdio.h>
int square(int x) {
return x * x;
}
int main() {
int a = square(3);
int b = square(a + 1);
printf("%d %d\n", a, b);
return 0;
}- Line 8: main calls square with 3.
- Line 4: Inside square, x is 3. It returns 9.
- Line 8: Back in main: a gets the 9.
- Line 4: Called again, this time x is a + 1 = 10. Returns 100.
- Line 9: b gets 100.
- Line 10: Printed.
void functions
#include <stdio.h>
void line(int n) {
for (int i = 0; i < n; i++) printf("-");
printf("\n");
}
int main() {
line(3);
line(1);
return 0;
}What does this print?
- --- -
- - ---
- ----
Show the answer
--- - Each call prints n dashes and a new line: 3 first, then 1.
Exercise: Write max()
Write int max(int a, int b) that returns the larger of the two. main already reads three numbers and prints the biggest using it.
Exercise: Write power()
Write long long power(int base, int exp) using a loop (no math.h). Read base and exp (exp ≥ 0) and print the result.