Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Arrays in C

What is an Array?

An array is a collection of variables that are accessed with an index number. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

For example, if you want to store 100 integers, you can create an array that holds 100 integers, instead of declaring 100 separate integer variables.

Declaring Arrays

To declare an array in C, specify the type of the elements and the number of elements required by an array as follows:

type arrayName[arraySize];

This is called a single-dimensional array. The 'arraySize' must be an integer constant greater than zero and 'type' can be any valid C data type. For example:

int numbers[10];

Initializing Arrays

You can initialize an array in C either one by one or using a single statement as follows:

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

The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the array name. For example:

int value = numbers[2];

The above statement will take the third element from the array and assign it to the variable 'value'. Remember that array indices start from zero, so the first element is numbers[0].

Example Program

Here is a complete example that demonstrates declaration, initialization, and accessing of array elements:

#include <stdio.h>

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};
    int i;

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

    return 0;
}

The output of the above program will be:

Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50

Conclusion

Arrays are a fundamental concept in C and are used to store multiple values of the same type. Understanding how to declare, initialize, and access arrays is essential for effective programming in C. This tutorial has provided a comprehensive introduction to arrays, including examples to illustrate key points.