Arrays
Read · 1 of 5
One name, many boxes
int marks[5]; makes 5 int boxes in a row: marks[0] to marks[4]. Positions start at 0, so the last one is size − 1.
C doesn't check positions for you. Reading marks[5] doesn't stop with an error: it quietly reads whatever memory comes next. Keep every index between 0 and size − 1.
Read this lesson as text
A row of boxes numbered from 0.
One name, many boxes
int marks[5]; makes 5 int boxes in a row: marks[0] to marks[4]. Positions start at 0, so the last one is size − 1.
C doesn't check positions for you. Reading marks[5] doesn't stop with an error: it quietly reads whatever memory comes next. Keep every index between 0 and size − 1.
Fill it, then use it
#include <stdio.h>
int main() {
int n, a[100], sum = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
for (int i = 0; i < n; i++) sum += a[i];
printf("first %d, last %d, sum %d\n", a[0], a[n - 1], sum);
return 0;
}- Line 5: n is 4: we'll use a[0] to a[3] of the 100 boxes.
- Line 6: Read 4 numbers into positions 0, 1, 2, 3.
- Line 7: Add them up: 3 + 8 + 1 + 6.
- Line 8: The last element is at n − 1, not n.
Shifting things around
#include <stdio.h>
int main() {
int a[4] = {5, 6, 7, 8};
for (int i = 0; i < 3; i++) a[i] = a[i + 1];
printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);
return 0;
}What does this print?
- 6 7 8 8
- 5 5 6 7
- 6 7 8 5
Show the answer
6 7 8 8 Each element takes the value of the one after it. The last one isn't overwritten, so 8 stays.
Exercise: Print it backwards
Read n (1 to 100), then n numbers. Print them in reverse order, separated by spaces.
Exercise: Above average
Read n (1 to 100) and n marks. Print how many marks are strictly above the average.