Lesson 27: Introduction to Arrays (1D Arrays)
An array is a collection of elements of the same data type stored in contiguous memory locations. Arrays provide a way to handle a large number of related variables efficiently.
Array Declaration
To declare an array, specify the type, the name, and the size (number of elements) in square brackets.
Syntax: data_type array_name[size];
c int scores[5]; // Declares an array of 5 integers double prices[100]; // Declares an array of 100 doubles
Array Indexing
C arrays are zero-indexed. The first element is at index 0, and the last element of an array of size $N$ is at index $N-1$.
Accessing Elements
c scores[0] = 95; // Assigns 95 to the first element int last_score = scores[4]; // Accesses the last element (if size is 5)
Array Initialization
1. Initialization at Declaration
c int numbers[5] = {10, 20, 30, 40, 50};
2. Initialization without Explicit Size
The compiler calculates the size based on the number of initializers.
c int data[] = {1, 2, 3}; // Size is automatically 3
3. Partial Initialization
If fewer values are provided than the size, the remaining elements are automatically initialized to zero.
c int status[5] = {1, 2}; // status[2], status[3], status[4] are 0