C
Array helpers
Add array processing functions.
Array helpers
The fourth lesson defines arr_max and arr_sum. arr_max returns the largest element of an int array; arr_sum returns the sum of all elements.
Both iterate with a for loop. arr_max keeps an m variable and compares each step; arr_sum keeps an s accumulator and adds each step. The array length is a parameter; this is required because C arrays have no built-in size. The previous lesson's solution is in the starting code.
arr_max implementation
arr_max takes the first element as the initial value and walks the array looking for the largest. Form: 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; }.
The first element is already m; so the loop starts at i = 1. Each step checks a[i] > m; if true, m is updated. After the loop, m is the largest. This pattern is standard in statistics and game score calculations.
Exercise Add arr_max and arr_sum
Below the existing definitions, write int arr_max(int *a, int n) that starts with the first element and finds the largest with for (int i = 1; i < n; i++). Write int arr_sum(int *a, int n) that sums with for (int i = 0; i < n; i++) s += a[i];. In main declare int arr[3] = {5, -3, 8};, then add printf("%d\n", arr_max(arr, 3)); and printf("%d\n", arr_sum(arr, 3));.
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;
}
int main(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));
return 0;
}
Test yourself
-
Which function returns the largest element of an array?
- arr_sum
- str_len
- arr_max
- num_abs
Show answer
arr_max — arr_max finds the largest element in the array.
-
Match the array helpers
- arr_max([5,-3,8])
- Returns 8
- arr_sum([5,-3,8])
- Returns 10
- arr_max([1,1,1])
- Returns 1
- arr_sum([1,1,1])
- Returns 3
-
Complete the arr_sum loop bound
int arr_sum(int *a, int n) {
int s = 0;
for (int i = 0; i < ____; i++) s += a[i];
return s;
}
Show answer
int arr_sum(int *a, int n) {
int s = 0;
for (int i = 0; i < n; i++) s += a[i];
return s;
}
Next lesson: Putting it together