We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

C Arrays

If you're used to Lists in Python, Arrays in C are similar, but a bit lower level.

An array is a fixed-size, ordered collection of elements. Like Python lists, they are indexed by integers, starting at zero. Unlike Python lists, they can only hold elements of the same type. They are stored in contiguous memory, like structs.

Integer Array

int numbers[5] = {1, 2, 3, 4, 5};

Iterating Over an Array

In C, there is no for x in list: syntax. Instead, you must iterate over them using a for loop with an index (or some other conditional loop)

#include <stdio.h>

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};

    // Iterate and print each element
    for (int i = 0; i < 5; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    return 0;
}

Output:

1 2 3 4 5

Updating Values in an Array

The syntax for updating values in an array is the same as how you access them:

arr[index] = value

Using our numbers example:

#include <stdio.h>

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};

    // Update some values
    numbers[1] = 20;
    numbers[3] = 40;

    // Print updated array
    for (int i = 0; i < 5; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    return 0;
}

Output:

1 20 3 40 5

Assignment

Complete the update_file function. The filedata array is a large 200-integer array representing a Sneklang source file. Each integer in the array represents a special piece of data.

  • Index 1 is the number of lines
  • Index 2 is the filetype
  • Index 199 is always 0

Update the function so that it:

By modifying the array within your function, you're changing the values of the original array, not just a copy. More on that later.