Lesson 20: Arrays

Learn how to declare, initialize, and access C arrays, with clear memory diagrams.

📖 What to learn on this page
✅ Must-know essentials
  • int a[5]; declares an array of 5
  • Index from a[0] to a[4]
  • Out-of-bounds access is a bug
⭐ Read if you have time

Array — group values of the same type

Creating a separate variable for every value becomes unwieldy. An array lets you manage many values of the same type under one name .
❌ Separate variables…
int score1 = 80;
int score2 = 95;
int score3 = 72;
// A hundred students? This does not scale! 
⭕ One array…
int score[100];
score[0] = 80;
score[1] = 95;
// A for loop processes all elements 
An array stores values of the same type in contiguous memory, using an index to select an element. Array indices start at zero .
int a[5] = {10, 20, 30, 40, 50};
printf("%d\n", a[0]); // → 10
printf("%d\n", a[4]); // → 50
⚠️ int a[5] in 5 gives the number of elements; a[5] does not exist in the array!
This is a common beginner mistake.
● Declaration in [5]: specify the number of elements → reserve memory for five elements
● Access in [ ]: specify a position → only 0 through 4 are valid

int a[5]; // Reserve five elements: a[0] through a[4]
a[0] = 10; // ✅ First element
a[4] = 50; // ✅ Last element
a[5] = 99; // ❌ Out of bounds: undefined behavior, possibly memory corruption

The five elements run from a[0]through a[4] only . Distinguish the declared size, 5, from the final index, 4.

Why this design? An index is an offset from the first element. The first has offset 0; in a five-element array, the last has offset 4.
💡 The risk of out-of-bounds access: In C, expressions such as a[5]or a[100] can compile successfully , sometimes without warnings. At runtime they can corrupt data, crash with a segmentation fault, or appear to work until a bug surfaces later.
In a loop, i < 5 restricts indices to 0–4. i <= 5 instead accesses a[5], causing an off-by-one error.

Declaration and initialization patterns

When you initialize an array with = { ... }, any omitted elements are automatically initialized to zero.
int a[5] = {1, 2, 3, 4, 5};  // Specify every element 
int b[5] = {1, 2};        // → {1, 2, 0, 0, 0}: remaining elements are zero 
int c[5] = {0};           // → All elements zero: a common pattern 
int d[] = {1, 2, 3};      // Omitted size: inferred as three elements 
int e[5];                // No initializer: indeterminate values for this local array 
Syntax Result Key point
{1,2,3,4,5}1, 2, 3, 4, 5Every element specified
{1,2}1, 2, 0, 0, 0Remaining elements zero
{0}0, 0, 0, 0, 0All-zero initialization
int d[] = {…}Count inferred Size can be omitted
int e[5];Indeterminate values Initialize before use
Without an initializer =, a local automatic array's contents are indeterminate . Before reading elements, initialize them with {0} or assign values explicitly.

Step execution — array with for loop

array_demo.c

Variable state

NameTypeValue

Array memory

Standard output

 

Array patterns with for: sum, maximum, and search

These common patterns combine arrays with for loops. i < N keeps indices in range.

Find the sum

int a[5] = {10, 20, 30, 40, 50};
int sum = 0;                  // Initialize the accumulator to zero 
for (int i = 0; i < 5; i++) {
    sum += a[i];
}
printf("%d\n", sum);          // → 150

Find the maximum

int max = a[0];               // Start from the first element (important) 
for (int i = 1; i < 5; i++) {
    if (a[i] > max) max = a[i];
}
printf("%d\n", max);          // → 50
⚠️ Starting the maximum at max = 0 fails when the array contains only negative values . Initialize it using max = a[0], the value of the first element .

Find a particular value

int target = 30, found = -1;
for (int i = 0; i < 5; i++) {
    if (a[i] == target) { found = i; break; }
}
printf("%d\n", found);        // → 2 (the index where the value was found) 
Summing, finding a maximum, and searching all use the pattern iterate from 0 through N-1 . Use the condition i < N(<= would go out of bounds).

Try it yourself: arrays

my_array.c
Output
Press Run…
⚠️ Is "Average = 80" really right? — the integer-division trap
The sum is 80+65+92+78+88 = 403; the true average is 403 ÷ 5 = 80.6.
However, the screen displays 80 because C performs int divided by int truncates toward zero here ( int / int → int).
To obtain 80.6 correctly, use
double avg = (double)sum / 5; to convert one operand to double before division.
The output is printf("Average = %.1f\n", avg); (%.1f for one decimal place).
💡 "Integer division truncates" is the top gotcha for C beginners. See Lesson 8 (Arithmetic operators) for more.
💡 More things to try

Related Lessons

Loops
Lesson 16: for & while Loops
How to use for and while loops in C.
Arrays & Strings
Lesson 23: Strings
How to work with strings in C: char arrays, strcpy, strlen, strcmp.
Reference
C Cheat Sheet
Quick reference for printf, operators, types, and more.
Practice problems for this lessonArrays: 13 practice problemsWrite code in your browser and get it checked automatically. Hints and solutions included →
← Previous lesson
Lesson 19: Debugging
Next lesson →
Lesson 21: Quiz (Arrays)

Review Quiz

Check your understanding of this lesson!

Q1. How many elements does int a[5]; allocate?

4
5
6

a[5] gives you 5 elements, from a[0] through a[4].

Q2. What index does a C array start from?

0
1
Any

C array indices always start at 0. In a[5], a[0] is the first element.

Q3. For int a[3] = {1, 2};, what is the value of a[2]?

Undefined
0
2

When an array is partially initialized, the leftover elements are zero-initialized. So a[2] is 0.

Share this article
Share on X (Twitter) Share on Facebook Send on LINE Hatena