Declaring and Initializig Arrays

Lesson 5.1: Declaring and Initializing Arrays


In this lesson, you'll learn how to create and work with arrays in C. Arrays are fundamental data structures that allow you to store multiple values of the same type under a single name.


What is an Array?


Think of an array as a collection of boxes, all lined up in a row. Each box (element) can hold a value, and you can access each element using its position (index) in the array. The index starts from zero for the first element.


Array Declaration


To declare an array, you specify:


The data type of the elements it will hold (e.g., int, float, char).

The name of the array.

The size of the array within square brackets []. The size determines the number of elements the array can store.

C

int numbers[5];   // Declares an array of 5 integers

float grades[10];  // Declares an array of 10 floating-point numbers

char letters[26]; // Declares an array of 26 characters


Array Initialization


You can initialize an array at the time of declaration or later in your code.


Initialization at Declaration:

C

int numbers[5] = {10, 20, 30, 40, 50}; // Initializes the array with values

char vowels[5] = {'a', 'e', 'i', 'o', 'u'};


Partial Initialization: If you provide fewer initializers than the size of the array, the remaining elements will be automatically initialized to zero (for numeric types) or null characters ('\0') for char arrays.

C

int numbers[5] = {1,2}; // numbers[2] to numbers[4] will be 0

Later Initialization:

C

int numbers[3]; // Declare an array

numbers[0] = 1;  

numbers[1] = 2; 

numbers[2] = 3; 

Important Considerations


Fixed Size: The size of an array is determined at compile time and cannot be changed during the program's execution.

Index Range: Valid array indices range from 0 to size - 1. Trying to access an element outside this range will result in undefined behavior (likely a program crash).

Example: Working with Arrays


C

#include <stdio.h>


int main() {

    int scores[4] = {85, 92, 78, 64};

    float average = 0.0;


    for (int i = 0; i < 4; i++) {

        average += scores[i];  // Sum up the scores

    }

    average /= 4;           // Calculate the average


    printf("Average score: %.2f\n", average); 

    return 0;

}

Key Points


Arrays are used to store multiple elements of the same type.

Elements are accessed by their index, starting from 0.

Arrays have a fixed size, determined at compile time.

You can initialize arrays at declaration or later in your code.

Let me know if you'd like more explanation on a particular topic!

Course Syllabus