Array in C Programming – Explained for Beginners
Introduction
In C programming, an array is a collection of elements of the same data type stored at contiguous memory locations.
It helps you store multiple values in a single variable, instead of declaring separate variables for each value.
Example: Instead of writing
int num1 = 10, num2 = 20, num3 = 30;
You can use an array:
int numbers[3] = {10, 20, 30};
Why Use Arrays?
To store large amounts of data easily.
To access data quickly using an index.
To perform operations (sorting, searching) on bulk data.
To avoid writing multiple variables.
Declaration of Arrays
datatype array_name[size];
datatype → Type of data (int, float, char, etc.)
array_name → Name of the array
size → Number of elements in the array
Example:
int marks[5]; // Array to store 5 integers
Initialization of Arrays
At Declaration
int marks[5] = {90, 85, 70, 95, 100};
Without Size (Compiler counts automatically)
int marks[] = {90, 85, 70, 95, 100};
Partial Initialization (remaining elements set to 0)
int marks[5] = {90, 85}; // → {90, 85, 0, 0, 0}
Accessing Array Elements
Array elements are accessed using an index (starting from 0).
#include <stdio.h>
int main() {
int marks[5] {90, 85, 70, 95, 100};
printf("First mark = %d\n", marks[0]); // Output: 90
printf("Third mark = %d\n", marks[2]); // Output: 70
return 0;
}
Traversing an Array (Using Loop)
#include <stdio.h>
int main() {
int marks[5] = {90, 85, 70, 95, 100};
for(int i = 0; i < 5; i++) {
printf("marks[%d] = %d\n", i, marks[i]);
}
return 0;
}
Output:
marks[0] = 90
marks[1] = 85
marks[2] = 70
marks[3] = 95
marks[4] = 100
Types of Arrays in C
One-Dimensional Array (1D)
Linear list of elements.
Example:
int arr[5] = {1, 2, 3, 4, 5};
Two-Dimensional Array (2D)
Like a table (rows & columns).
Example:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Accessing element: matrix[1][2] = 6
Multi-Dimensional Array
More than 2 dimensions (rare in beginner-level).
Example Program – Sum of Array Elements
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
int sum = 0;
for(int i = 0; i < 5; i++) {
sum += numbers[i];
}
printf("Sum = %d", sum);
return 0;
}
Output:
Sum = 150
Advantages of Arrays
Easy to manage multiple values.
Faster data access using index.
Useful for loops, sorting, searching.
Limitations of Arrays
Fixed size (cannot be changed once declared).
Stores only one data type at a time.
No built-in bounds checking (risk of errors if index goes out of range).