An array is a collection of data items of the same type stored in contiguous (side-by-side) memory locations. Instead of creating 50 separate variables for 50 students' grades, you create one array.
1. Declaration and Initialization
To create an array, you specify the type, the name, and the size in square brackets [].
#include <stdio.h>
int main() {
// Declaration and initialization
int marks[5] = {90, 85, 70, 95, 80};
// Accessing elements (Indices start at 0!)
printf("First element: %d\n", marks[0]);
printf("Third element: %d\n", marks[2]);
// Modifying an element
marks[1] = 88;
printf("Updated second element: %d\n", marks[1]);
return 0;
}Expected Output:
First element: 90
Third element: 70
Updated second element: 882. Looping Through Arrays
Arrays and for loops are best friends. Since indices are numeric, we use the loop counter i to visit every "bucket" in the array.
#include <stdio.h>
int main() {
int numbers[4];
// Input: Taking values from user
printf("Enter 4 integers:\n");
for(int i = 0; i < 4; i++) {
scanf("%d", &numbers[i]);
}
// Output: Printing the array
printf("The array contains: ");
for(int i = 0; i < 4; i++) {
printf("%d ", numbers[i]);
}
return 0;
}Expected Output:
Enter 4 integers:
10
20
30
40
The array contains: 10 20 30 403. Two-Dimensional (2D) Arrays
A 2D array is like a table with rows and columns. This is how you would represent a matrix or a seating chart.
#include <stdio.h>
int main() {
// A 2x3 matrix (2 rows, 3 columns)
int matrix[2][3] = {
{1, 2, 3}, // Row 0
{4, 5, 6} // Row 1
};
printf("Element at row 1, col 2: %d\n", matrix[1][2]); // Prints 6
return 0;
}Expected Output:
Element at row 1, col 2: 6Important Rules for Arrays
Zero-Based Indexing: The first element is always
[0]. If an array has 10 elements, the last index is[9].No Bounds Checking: C will not stop you if you try to access
marks[100]in a size-5 array. This is called "Array Out of Bounds" and usually leads to a crash or garbage data.Fixed Size: Once declared, you cannot change the size of a standard array. (To do that, you'd need the Dynamic Memory Allocation we discussed earlier).