Arrays in C: From Basics to Advanced
Last Updated on: 20th Jul 2025 23:29:39 PM
Arrays in C are powerful data structures that allow you to store multiple elements of the same type in a contiguous block of memory. Think of an array as a row of lockers, each holding a value you can access by its position. This tutorial covers arrays from beginner to advanced levels, including their declaration, initialization, and advanced applications. With unique examples, clear explanations, and outputs, this guide is designed to be engaging for both beginners and seasoned programmers. Let’s dive into the world of arrays!
1. Introduction to Arrays
An array in C is a collection of elements of the same data type stored in contiguous memory locations, accessed using an index. Arrays are ideal for storing lists of data, such as numbers, characters, or custom types.
Key Features:
-
Fixed size, determined at declaration.
-
Zero-based indexing (first element at index 0).
-
Efficient for accessing and manipulating multiple values.
Why Use Arrays?
-
Organize data (e.g., student marks, product prices).
-
Enable efficient iteration using loops.
-
Serve as the foundation for more complex data structures (e.g., matrices, stacks).
2. Array Syntax in C
Declaration:
data_type array_name[size]; // Single-dimensional
data_type array_name[rows][cols]; // Multi-dimensional
-
data_type: Type of elements (e.g., int, float, char).
-
array_name: Name of the array.
-
size, rows, cols: Number of elements (fixed at compile time).
Initialization:
data_type array_name[size] = {value1, value2, ..., valueN};
data_type array_name[rows][cols] = {{val11, val12}, {val21, val22}};
Accessing Elements:
array_name[index]; // Single-dimensional
array_name[row][col]; // Multi-dimensional
Input with scanf:
scanf("%d", &array_name[index]); // Single-dimensional
scanf("%d", &array_name[row][col]); // Multi-dimensional
3. Types of Arrays
-
Single-Dimensional Arrays: A linear list of elements (e.g., a list of scores).
-
Multi-Dimensional Arrays: Arrays of arrays, like matrices (e.g., 2D for grids, 3D for 3D models).
-
Dynamic Arrays: Simulated using pointers and dynamic memory allocation (e.g., malloc).
4. Single-Dimensional Arrays
Basic Example: Store and Print Student Marks
This example declares an array to store marks and prints them.
#include <stdio.h>
int main() {
int marks[5] = {85, 90, 78, 92, 88};
printf("Student Marks:\n");
for (int i = 0; i < 5; i++) {
printf("Student %d: %d\n", i + 1, marks[i]);
}
return 0;
}
Output:
Student Marks:
Student 1: 85
Student 2: 90
Student 3: 78
Student 4: 92
Student 5: 88
Explanation:
-
The array marks stores 5 integers, initialized with values.
-
A for loop iterates through indices 0 to 4, printing each element.
-
The index i accesses marks[i] to retrieve the value.
Basic Example 2: Store and Average User-Entered Prices
This program takes 5 product prices from the user via scanf and calculates their average.
#include <stdio.h>
#define SIZE 5
int main() {
float prices[SIZE];
float sum = 0.0;
printf("Enter %d product prices:\n", SIZE);
for (int i = 0; i < SIZE; i++) {
printf("Price %d: ", i + 1);
scanf("%f", &prices[i]);
sum += prices[i];
}
printf("\nEntered Prices:\n");
for (int i = 0; i < SIZE; i++) {
printf("Price %d: %.2f\n", i + 1, prices[i]);
}
printf("Average price: %.2f\n", sum / SIZE);
return 0;
}
Output (example user input: 10.50, 20.75, 15.25, 30.00, 25.50):
Enter 5 product prices:
Price 1: 10.50
Price 2: 20.75
Price 3: 15.25
Price 4: 30.00
Price 5: 25.50
Entered Prices:
Price 1: 10.50
Price 2: 20.75
Price 3: 15.25
Price 4: 30.00
Price 5: 25.50
Average price: 20.40
Explanation:
-
The prices array stores 5 float values, input using scanf.
-
A loop collects each price and adds it to sum.
-
The program prints all prices and their average, using %.2f for two decimal places.
Basic Example 3: Store and Analyze User-Entered Scores
This program takes 5 test scores from the user via scanf and finds the highest score.
#include <stdio.h>
#define SIZE 5
int main() {
int scores[SIZE];
printf("Enter %d test scores:\n", SIZE);
for (int i = 0; i < SIZE; i++) {
printf("Score %d: ", i + 1);
scanf("%d", &scores[i]);
}
int max = scores[0];
for (int i = 1; i < SIZE; i++) {
if (scores[i] > max) {
max = scores[i];
}
}
printf("\nScores entered:\n");
for (int i = 0; i < SIZE; i++) {
printf("Score %d: %d\n", i + 1, scores[i]);
}
printf("Highest score: %d\n", max);
return 0;
}
Output (example user input: 78, 92, 85, 88, 95):
Enter 5 test scores:
Score 1: 78
Score 2: 92
Score 3: 85
Score 4: 88
Score 5: 95
Scores entered:
Score 1: 78
Score 2: 92
Score 3: 85
Score 4: 88
Score 5: 95
Highest score: 95
Explanation:
-
The scores array stores 5 integers, input using scanf in a loop.
-
The loop prompts for each score, storing it at scores[i].
-
A second loop finds the maximum score by comparing each element to max.
-
The program prints all scores and the highest one.
5. Multi-Dimensional Arrays
Multi-dimensional arrays, particularly 2D arrays, are used for matrices, game boards, or tabular data. This section covers:
-
Taking input and printing a matrix.
-
Addition of two matrices.
-
Matrix multiplication.
-
Matrix transpose.
5.1. Basic Example: Input and Print a 2D Matrix
This program takes a 3x3 matrix from the user and displays it.
#include <stdio.h>
#define ROWS 3
#define COLS 3
int main() {
int matrix[ROWS][COLS];
printf("Enter elements for a %dx%d matrix:\n", ROWS, COLS);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("Element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
printf("\nEntered Matrix:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%4d", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Output (example user input: 1, 2, 3, 4, 5, 6, 7, 8, 9):
Enter elements for a 3x3 matrix:
Element [0][0]: 1
Element [0][1]: 2
Element [0][2]: 3
Element [1][0]: 4
Element [1][1]: 5
Element [1][2]: 6
Element [2][0]: 7
Element [2][1]: 8
Element [2][2]: 9
Entered Matrix:
1 2 3
4 5 6
7 8 9
Explanation:
-
The matrix array is a 3x3 2D array.
-
Nested loops with scanf collect user input for each element.
-
A second set of nested loops prints the matrix, using %4d for aligned formatting.
5.2. Basic Example: Addition of Two 2D Matrices
This program adds two 2x2 matrices.
#include <stdio.h>
int main() {
int matrix1[2][2] = {{1, 2}, {3, 4}};
int matrix2[2][2] = {{5, 6}, {7, 8}};
int result[2][2];
printf("Matrix Addition:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Matrix Addition:
6 8
10 12
Explanation:
-
Two 2x2 matrices (matrix1, matrix2) are initialized.
-
Nested for loops iterate over rows (i) and columns (j), adding corresponding elements.
-
The result array stores the sum, printed in matrix format.
This program takes two 2x2 matrices from the user and computes their sum.
#include <stdio.h>
#define ROWS 2
#define COLS 2
int main() {
int matrix1[ROWS][COLS], matrix2[ROWS][COLS], sum[ROWS][COLS];
printf("Enter elements for first %dx%d matrix:\n", ROWS, COLS);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("Matrix1[%d][%d]: ", i, j);
scanf("%d", &matrix1[i][j]);
}
}
printf("Enter elements for second %dx%d matrix:\n", ROWS, COLS);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("Matrix2[%d][%d]: ", i, j);
scanf("%d", &matrix2[i][j]);
}
}
printf("\nSum of Matrices:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
printf("%4d", sum[i][j]);
}
printf("\n");
}
return 0;
}
Output (example user input: Matrix1 = {1, 2, 3, 4}, Matrix2 = {5, 6, 7, 8}):
Enter elements for first 2x2 matrix:
Matrix1[0][0]: 1
Matrix1[0][1]: 2
Matrix1[1][0]: 3
Matrix1[1][1]: 4
Enter elements for second 2x2 matrix:
Matrix2[0][0]: 5
Matrix2[0][1]: 6
Matrix2[1][0]: 7
Matrix2[1][1]: 8
Sum of Matrices:
6 8
10 12
Explanation:
-
Two 2x2 matrices (matrix1, matrix2) are filled using scanf in nested loops.
-
The sum array stores the element-wise addition (matrix1[i][j] + matrix2[i][j]).
-
The result is printed in a grid format with %4d for alignment.
5.3. Intermediate Example: Matrix Multiplication
This program multiplies two 2x2 matrices entered by the user.
#include <stdio.h>
#define ROWS 2
#define COLS 2
int main() {
int matrix1[ROWS][COLS], matrix2[ROWS][COLS], product[ROWS][COLS];
printf("Enter elements for first %dx%d matrix:\n", ROWS, COLS);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("Matrix1[%d][%d]: ", i, j);
scanf("%d", &matrix1[i][j]);
}
}
printf("Enter elements for second %dx%d matrix:\n", ROWS, COLS);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("Matrix2[%d][%d]: ", i, j);
scanf("%d", &matrix2[i][j]);
}
}
// Matrix multiplication
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
product[i][j] = 0;
for (int k = 0; k < COLS; k++) {
product[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
printf("\nProduct of Matrices:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%4d", product[i][j]);
}
printf("\n");
}
return 0;
}
Output (example user input: Matrix1 = {1, 2, 3, 4}, Matrix2 = {5, 6, 7, 8}):
Enter elements for first 2x2 matrix:
Matrix1[0][0]: 1
Matrix1[0][1]: 2
Matrix1[1][0]: 3
Matrix1[1][1]: 4
Enter elements for second 2x2 matrix:
Matrix2[0][0]: 5
Matrix2[0][1]: 6
Matrix2[1][0]: 7
Matrix2[1][1]: 8
Product of Matrices:
19 22
43 50
Explanation:
-
Two 2x2 matrices are input using scanf.
-
The product array is computed using the matrix multiplication formula: product[i][j] = Σ(matrix1[i][k] * matrix2[k][j]).
-
Three nested loops perform the multiplication: i for rows, j for columns, k for summation.
-
The result is printed with %4d for alignment.
5.4. Intermediate Example: Matrix Transpose
This program takes a 3x3 matrix from the user and computes its transpose.
#include <stdio.h>
#define ROWS 3
#define COLS 3
int main() {
int matrix[ROWS][COLS], transpose[COLS][ROWS];
printf("Enter elements for a %dx%d matrix:\n", ROWS, COLS);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("Element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
// Compute transpose
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
transpose[j][i] = matrix[i][j];
}
}
printf("\nOriginal Matrix:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%4d", matrix[i][j]);
}
printf("\n");
}
printf("\nTranspose Matrix:\n");
for (int i = 0; i < COLS; i++) {
for (int j = 0; j < ROWS; j++) {
printf("%4d", transpose[i][j]);
}
printf("\n");
}
return 0;
}
Output (example user input: 1, 2, 3, 4, 5, 6, 7, 8, 9):
Enter elements for a 3x3 matrix:
Element [0][0]: 1
Element [0][1]: 2
Element [0][2]: 3
Element [1][0]: 4
Element [1][1]: 5
Element [1][2]: 6
Element [2][0]: 7
Element [2][1]: 8
Element [2][2]: 9
Original Matrix:
1 2 3
4 5 6
7 8 9
Transpose Matrix:
1 4 7
2 5 8
3 6 9
Explanation:
-
The user inputs a 3x3 matrix using scanf.
-
The transpose array is computed by swapping rows and columns (transpose[j][i] = matrix[i][j]).
-
Both the original and transposed matrices are printed with %4d for alignment.
6. Array Operations
Common operations include traversal, searching, sorting, and manipulation.
Example 1: Linear Search in an Array
This program searches for a value in an array.
#include <stdio.h>
int main() {
int arr[6] = {10, 20, 30, 40, 50, 60};
int target = 40, found = 0;
for (int i = 0; i < 6; i++) {
if (arr[i] == target) {
printf("%d found at index %d\n", target, i);
found = 1;
break;
}
}
if (!found) {
printf("%d not found in the array\n", target);
}
return 0;
}
Output:
40 found at index 3
Explanation:
-
The for loop iterates through the array, checking each element against target.
-
If found, it prints the index and uses break to exit early.
-
The found flag ensures a message is printed if the target isn’t found.
Example 2: Unique Element Counter
This program takes user input for an array and counts unique elements.
#include <stdio.h>
#define SIZE 6
int main() {
int arr[SIZE], unique[SIZE] = {0}, uniqueCount = 0;
printf("Enter %d integers:\n", SIZE);
for (int i = 0; i < SIZE; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
for (int i = 0; i < SIZE; i++) {
int isUnique = 1;
for (int j = 0; j < uniqueCount; j++) {
if (arr[i] == unique[j]) {
isUnique = 0;
break;
}
}
if (isUnique) {
unique[uniqueCount++] = arr[i];
}
}
printf("\nArray elements:\n");
for (int i = 0; i < SIZE; i++) {
printf("%d ", arr[i]);
}
printf("\nUnique elements: %d\n", uniqueCount);
printf("Unique values: ");
for (int i = 0; i < uniqueCount; i++) {
printf("%d ", unique[i]);
}
printf("\n");
return 0;
}
Output (example user input: 3, 5, 3, 7, 5, 8):
Enter 6 integers:
Element 1: 3
Element 2: 5
Element 3: 3
Element 4: 7
Element 5: 5
Element 6: 8
Array elements:
3 5 3 7 5 8
Unique elements: 4
Unique values: 3 5 7 8
Explanation:
-
The arr array stores 6 integers input via scanf.
-
The unique array tracks unique elements, and uniqueCount counts them.
-
For each element in arr, the program checks if it’s already in unique. If not, it’s added.
-
The program prints the original array and the unique elements.
Example 3: Find Duplicates in an Array
This program takes user input for a 1D array and identifies duplicate elements.
#include <stdio.h>
#define SIZE 6
int main() {
int arr[SIZE], freq[100] = {0}; // Assume values < 100
printf("Enter %d integers:\n", SIZE);
for (int i = 0; i < SIZE; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
freq[arr[i]]++;
}
printf("\nArray elements:\n");
for (int i = 0; i < SIZE; i++) {
printf("%d ", arr[i]);
}
printf("\nDuplicates:\n");
int found = 0;
for (int i = 0; i < 100; i++) {
if (freq[i] > 1) {
printf("%d appears %d times\n", i, freq[i]);
found = 1;
}
}
if (!found) {
printf("No duplicates found.\n");
}
return 0;
}
Output (example user input: 4, 2, 4, 7, 2, 9):
Enter 6 integers:
Element 1: 4
Element 2: 2
Element 3: 4
Element 4: 7
Element 5: 2
Element 6: 9
Array elements:
4 2 4 7 2 9
Duplicates:
2 appears 2 times
4 appears 2 times
Explanation:
-
The arr array stores 6 integers input via scanf.
-
The freq array counts occurrences of each value (assuming values < 100).
-
Elements with freq[i] > 1 are printed as duplicates.
7. Dynamic Arrays with Pointers
C arrays have a fixed size, but dynamic arrays can be created using malloc or calloc for flexible sizing at runtime.
Example: Dynamic Array Allocation
This program creates a dynamic array based on user input.
#include <stdio.h>
#include <stdlib.h>
int main() {
int size;
printf("Enter array size: ");
scanf("%d", &size);
int *arr = (int *)malloc(size * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
printf("You entered:\n");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
free(arr); // Free allocated memory
return 0;
}
Output (if user enters size 4 and elements 1, 2, 3, 4):
Enter array size: 4
Enter 4 elements:
1 2 3 4
You entered:
1 2 3 4
Explanation:
-
malloc allocates memory for size integers, checked for failure (NULL).
-
The user inputs elements, which are stored in the dynamic array.
-
The array is printed, and free releases the memory to prevent leaks.
7. Advanced Example: Latin Square Validator
A Latin square is an n×n matrix where each row and column contains unique symbols (e.g., 1 to n). This program validates a user-entered 3x3 Latin square.
#include <stdio.h>
#define N 3
int isLatinSquare(int square[N][N]) {
// Check rows
for (int i = 0; i < N; i++) {
int seen[N + 1] = {0};
for (int j = 0; j < N; j++) {
int num = square[i][j];
if (num < 1 || num > N || seen[num]) {
return 0;
}
seen[num] = 1;
}
}
// Check columns
for (int j = 0; j < N; j++) {
int seen[N + 1] = {0};
for (int i = 0; i < N; i++) {
int num = square[i][j];
if (num < 1 || num > N || seen[num]) {
return 0;
}
seen[num] = 1;
}
}
return 1;
}
int main() {
int square[N][N];
printf("Enter a 3x3 matrix (values 1 to 3):\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("Element [%d][%d]: ", i, j);
scanf("%d", &square[i][j]);
}
}
printf("\nEntered Matrix:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", square[i][j]);
}
printf("\n");
}
if (isLatinSquare(square)) {
printf("This is a valid Latin square!\n");
} else {
printf("This is not a valid Latin square.\n");
}
return 0;
}
Output (example user input: {1, 2, 3}, {3, 1, 2}, {2, 3, 1}):
Enter a 3x3 matrix (values 1 to 3):
Element [0][0]: 1
Element [0][1]: 2
Element [0][2]: 3
Element [1][0]: 3
Element [1][1]: 1
Element [1][2]: 2
Element [2][0]: 2
Element [2][1]: 3
Element [2][2]: 1
Entered Matrix:
1 2 3
3 1 2
2 3 1
This is a valid Latin square!
Explanation:
-
The user inputs a 3x3 matrix using scanf, with values expected to be 1 to 3.
-
The isLatinSquare function checks each row and column to ensure all numbers from 1 to 3 appear exactly once.
-
A seen array tracks used numbers, returning 0 if a number is out of range or repeated.
-
The program prints the matrix and validation result.
Why Arrays Are Essential
Arrays in C are crucial for:
-
Efficient Data Storage: Store lists or grids in a single variable.
-
Algorithm Support: Enable searching, sorting, and matrix operations.
-
Real-World Applications: Used in image processing, games, and data analysis.