Back to Blog

C in 100 Seconds: Arrays | Episode 10

Daryl WongDaryl Wong

Video: C in 100 Seconds: Store Five Numbers in One Variable — Arrays | Episode 10 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Arrays — Storing Multiple Values in C

C in 100 Seconds, Episode 10


When you need five numbers, you don't declare five variables. You use an array.

Declaring an Array

int nums[] = {10, 20, 30, 40, 50};

The compiler counts the elements for you when you provide an initializer. This creates five contiguous integers in memory.

Accessing Elements

Arrays are zero-indexed. The first element is at index 0:

nums[0]  // 10
nums[2]  // 30
nums[4]  // 50

The sizeof Trick

C arrays don't know their own length. But you can calculate it:

int len = sizeof(nums) / sizeof(nums[0]);

sizeof(nums) gives the total bytes of the array. sizeof(nums[0]) gives the size of one element. Divide them and you get the count.

Iterating

Combine the length calculation with a for loop:

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

Modifying Elements

You can change any element by assigning to its index:

nums[2] = 99;
printf("After change: nums[2] = %d\n", nums[2]);

Why Does This Matter?

Arrays are the foundation of data storage in C. Strings are arrays of characters. Dynamic memory is accessed through array-like syntax. Understanding arrays is a prerequisite for everything that comes next.

Full Code

#include <stdio.h>

int main() {
  int nums[] = {10, 20, 30, 40, 50};
  int len = sizeof(nums) / sizeof(nums[0]);

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

  nums[2] = 99;
  printf("\nAfter change: nums[2] = %d\n", nums[2]);

  return 0;
}

Compile and Run

gcc arrays.c -o arrays
./arrays

Next episode: Strings — working with text as character arrays.

Student code: github.com/GoCelesteAI/c-in-100-seconds/episode10