1-D arrays: store, index, and traverse
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
A row of boxes
- An array is a row of variables of the same type, kept side by side in memory.
int a[5];makes room for fiveints. They are one block, reached by number.- You can fill them when you create them:
int a[] = {10, 20, 30};makes an array of three.
Indexing from 0
- Each item has an index (a position). The first index is
0, not1. a[0]is the first item,a[1]the second, anda[n - 1]is the last in an array ofnitems.- Reading or writing outside the array (like
a[5]in a 5-item array) is a serious bug.
Traversing with a loop
- To visit every item, run an index from
0up ton - 1with aforloop. - Inside the loop, use
a[i]to read or change the item at positioni. - This is how you sum, count, or search an array.
Arrays don't know their own length
- An array does not carry its own size. A function cannot ask "how long are you?".
- So you always pass the length next to the array:
sum(a, n). - Use
const int a[]in a parameter to promise you will only read the array, not change it.
#include <stdio.h>
int main(void) {
int a[] = {10, 20, 30, 40};
int n = 4, total = 0;
for (int i = 0; i < n; i++) {
total += a[i];
}
printf("%d\n", total); // 100
return 0;
}
Now you try
- Pass both the array and its length
n, and loop the index from0ton - 1. - For the function tasks, do not write a
main— the checker provides one.
The array a and its length n are given. In main, add up all n items and print the total on its own line.
Click Run to see the output here.
Complete int sum(const int a[], int n) so it returns the total of the array's n items (0 when n is 0). Do not write a main.
Click Run to see the output here.
Complete void double_all(int a[], int n) so it doubles every item of the array, in place (no return value). Do not write a main.
Click Run to see the output here.