Chapter 5: Functions – Divide and Conquer
Learn how to use functions to organize and reuse code in C.
Chapter 5: Functions – Divide and Conquer
Table of Contents
- Table of Contents
- 5.1 Defining and Calling Functions
- 5.2 Function Parameters and Return Values
- 5.3 Exercises
- 5.4 Solutions
- 5.5 What’s Coming in the Next Chapter
5.1 Defining and Calling Functions
Functions help you break your code into reusable pieces:
1
2
3
4
5
6
7
8
9
int add(int a, int b) {
return a + b;
}
int main() {
int sum = add(2, 3);
printf("Sum: %d\n", sum);
return 0;
}
5.2 Function Parameters and Return Values
You can pass values to functions and get results back. Functions can have multiple parameters and return a value.
5.3 Exercises
- Write a function that multiplies two numbers.
- Write a function that returns the maximum of two integers.
- What happens if you forget to return a value from a non-void function?
5.4 Solutions
5.4.1 Solution 1
1
2
3
int multiply(int a, int b) {
return a * b;
}
5.4.2 Solution 2
1
2
3
int max(int a, int b) {
return (a > b) ? a : b;
}
5.4.3 Solution 3
The returned value is undefined; the result may be garbage.
5.5 What’s Coming in the Next Chapter
Next, you’ll learn about pointers—one of C’s most powerful features!
This post is licensed under CC BY 4.0 by the author.