Step 5 of 7
Modify an array in a function
Since a function receives the array's address, it can modify the caller's elements directly. This is called working in place: no second array is needed.
#include <stdio.h>
void add_bonus(int a[], int n, int bonus) {
for (int i = 0; i < n; i++) {
a[i] += bonus;
}
}
int main(void) {
int scores[] = {10, 20, 30};
add_bonus(scores, 3, 5);
printf("%d %d %d\n", scores[0], scores[1], scores[2]);
return 0;
}
15 25 35
Swapping two elements
To exchange two values you need a temporary variable. Writing a[i] = a[j]; a[j] = a[i]; loses the original a[i] on the first line, so both end up equal. Save one value first:
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
Reversing: two indexes moving inward
Reversing in place means swapping the first and last elements, then the second and second-to-last, and so on. Use two indexes: i starting at the front (0) and j at the back (n - 1). After each swap, move i forward and j backward. Stop when they meet or cross (i < j is the loop condition). If you kept going past the middle, you'd swap everything back again.
Check edge cases in your head: an array of 1 element (the loop shouldn't run), an even length (4 elements: swap 0-3 and 1-2), and an odd length (5 elements: the middle one stays put).
Your turn: write void reverse(int a[], int n) that reverses the array in place (no second array).