Arrays (1D & Contiguous Memory)

โš™๏ธ C Language ๐ŸŸข Lesson 8 of 20 ๐Ÿ“… 2026 Edition
An array lets you store many values of the same type under a single name, accessed by numeric position. Unlike Python lists, C arrays have a fixed size decided when they're created, and understanding this limitation is key to using them correctly.
1Declaring and Initializing Arrays
C Language โ–ถ Run Code
int numbers[5];                          // declares space for 5 ints, values are garbage/undefined
int scores[5] = {90, 85, 77, 92, 88};    // declares AND initializes
int grades[] = {70, 80, 90};             // size (3) inferred automatically from the values

Array indexing starts at 0, exactly like Python and most other languages: scores[0] is the first element, scores[4] is the last element of a 5-element array.

2Looping Through an Array
C Language โ–ถ Run Code
int scores[5] = {90, 85, 77, 92, 88};

for (int i = 0; i < 5; i++) {
    printf("%d\n", scores[i]);
}

C has no built-in way to ask an array how many elements it holds at runtime the way Python's len() does. Instead, calculate it using sizeof:

C Language โ–ถ Run Code
int size = sizeof(scores) / sizeof(scores[0]);  // total bytes รท bytes per element
3Modifying Array Elements
C Language โ–ถ Run Code
int scores[5] = {90, 85, 77, 92, 88};
scores[2] = 100;   // replace the third element
scores[0] += 5;    // add 5 to the first element

Unlike strings in many languages, arrays in C are always mutable โ€” you can freely change any element after creation, as long as you stay within the array's declared size.

4Arrays Have Fixed, Unchecked Bounds

A C array's size is fixed at creation and cannot grow. Worse, C does not automatically check whether an index is valid โ€” accessing scores[10] on a 5-element array doesn't raise a clean error like Python's IndexError. Instead, it reads or writes to whatever memory happens to sit next to your array, which can silently corrupt other data or crash your program unpredictably.

โš ๏ธ Common Mistake: Going Out of Array Bounds

This is one of the most dangerous C mistakes precisely because it often doesn't crash immediately โ€” scores[10] on a 5-element array might "work" and print a garbage number instead of failing loudly, hiding the bug until it causes unpredictable behavior somewhere else entirely. Always keep loop conditions strictly less than the array's actual size.

๐Ÿ’ป Try It Yourself

Create an array of 6 exam scores, calculate their average using a loop, and print the result.

C Language โ–ถ Run Code
#include <stdio.h>

int main() {
    int scores[6] = {88, 92, 79, 95, 84, 90};
    int sum = 0;

    for (int i = 0; i < 6; i++) {
        sum += scores[i];
    }

    printf("Average: %.2f\n", (float)sum / 6);
    return 0;
}
Run This in Our Compiler โ†’