C Arrays

Arrays let you store many values of the same type in a single variable, instead of declaring a separate variable for each value. If you needed to keep track of 100 test scores, declaring score1, score2, all the way to score100 would be painful. An array solves this by grouping the values together and giving you a simple number, called an index, to reach each one.

Creating an Array

To declare an array in C, you write the data type, the array name, and then the number of elements inside square brackets. The number in the brackets is the size of the array, which is how many values it can hold. You can also fill the array with values right away using curly braces.

Declaring and initializing an array

#include <stdio.h>

int main() {
  int myNumbers[4] = {25, 50, 75, 100};
  printf("First value: %d\n", myNumbers[0]);
  printf("Second value: %d\n", myNumbers[1]);
  return 0;
}
Note: Array indexes start at 0, not 1. This means the first element is myNumbers[0] and the last element of an array with 4 items is myNumbers[3].

Changing and Accessing Elements

You can read any element by using its index, and you can change an element by assigning a new value to that index. This makes arrays flexible: you set up the storage once, then update individual slots whenever you need to.

Changing an element by index

#include <stdio.h>

int main() {
  int myNumbers[4] = {25, 50, 75, 100};
  myNumbers[0] = 33;
  printf("New first value: %d\n", myNumbers[0]);
  return 0;
}

Looping Through an Array

Arrays and loops work well together. Because each element has a numbered index, you can use a for loop with a counter to visit every element one by one without repeating code.

Printing every element with a loop

#include <stdio.h>

int main() {
  int myNumbers[4] = {25, 50, 75, 100};
  for (int i = 0; i < 4; i++) {
    printf("Index %d holds %d\n", i, myNumbers[i]);
  }
  return 0;
}

Common array declarations

DeclarationMeaning
int nums[5];An empty array that can hold 5 integers
int nums[3] = {1, 2, 3};An array with 3 given values
int nums[] = {1, 2, 3};Size decided automatically from the values
char grade[4];An array that can hold 4 characters
Note: C does not check whether an index is valid. Reading or writing myNumbers[10] on a 4-element array is a mistake that can crash your program or produce garbage, so always stay inside the array's size.

Exercise: C Arrays

How are indices numbered for a C array such as int arr[5]?