C
Putting it together
Combine helper functions into a library.
Combining the helpers
In this final lesson you'll write a run_tests function that calls every helper. This way the library tests all behaviors through one entry point.
run_tests moves the test calls from main and adds printf("Hazır\n"); at the end. main only calls run_tests(). This pattern is common as a test driver in real libraries: the library user calls one function and sees all behaviors. At the end of the project you'll have six helpers and a test driver.
Exercise Add run_tests and simplify main
Below the existing definitions, add void run_tests(void). Move all printf calls from main into it (Modül hazır, str_len("Merhaba"), str_is_empty(""), num_abs(-7), num_sign(-5), int arr[3] = {5,-3,8};, arr_max(arr, 3), arr_sum(arr, 3)). Add printf("Hazır\n"); at the end. Make main's body run_tests(); return 0;.
Show example solution
#include <stdio.h>
int str_len(const char *s);
int str_is_empty(const char *s);
int num_abs(int n);
int num_sign(int n);
int arr_max(int *a, int n);
int arr_sum(int *a, int n);
int str_len(const char *s) {
int n = 0;
while (*s) { n++; s++; }
return n;
}
int str_is_empty(const char *s) {
return str_len(s) == 0;
}
int num_abs(int n) {
return n < 0 ? -n : n;
}
int num_sign(int n) {
if (n > 0) return 1;
if (n < 0) return -1;
return 0;
}
int arr_max(int *a, int n) {
int m = a[0];
for (int i = 1; i < n; i++) if (a[i] > m) m = a[i];
return m;
}
int arr_sum(int *a, int n) {
int s = 0;
for (int i = 0; i < n; i++) s += a[i];
return s;
}
void run_tests(void) {
printf("Modül hazır\n");
printf("%d\n", str_len("Merhaba"));
printf("%d\n", str_is_empty(""));
printf("%d\n", num_abs(-7));
printf("%d\n", num_sign(-5));
int arr[3] = {5, -3, 8};
printf("%d\n", arr_max(arr, 3));
printf("%d\n", arr_sum(arr, 3));
printf("Hazır\n");
}
int main(void) {
run_tests();
return 0;
}
Project complete
You've completed the five-lesson helper library project. You started from a module skeleton; added string, number and array helpers; and finally combined them with a run_tests test driver.
This structure is the foundation of real C projects: a header with declarations, a source with definitions and a test driver for usage. In the next group you'll see advanced string handling techniques and reuse some of these helpers in stronger forms. The code you accumulated will serve as a skeleton for upcoming projects.
Test yourself
-
Match helpers to category
- str_len, str_is_empty
- String helpers
- num_abs, num_sign
- Number helpers
- arr_max, arr_sum
- Array helpers
- run_tests
- Test driver
-
What does run_tests do?
- Defines a new type
- Allocates memory
- Reads user input
- Calls all helpers and prints results
Show answer
Calls all helpers and prints results — run_tests exercises all helpers and prints results.
-
Complete the run_tests call
int main(void) {
____();
return 0;
}
Show answer
int main(void) {
run_tests();
return 0;
}
Next lesson: Dynamic strings