What is an Array — and Why Use One?
Without arrays, storing 100 student marks would need 100 separate variables: int m1, m2, m3, ... m100; — and you could not loop through them. An array stores multiple values of the same type under one name, in a contiguous block of memory.
- Same type — all elements must be int, or all float, or all char, etc.
- Contiguous memory — all elements sit next to each other in RAM — no gaps
- Fixed size — the size is set at declaration and cannot change
- Index starts at 0 — first element is
arr[0], last isarr[n-1]
Without array vs with array — storing 5 marks
Declaring, Initialising & Indexing
| Method | Syntax | What happens |
|---|---|---|
| Declare only | int scores[5]; | 5 ints reserved — contain garbage |
| Declare + initialise | int scores[5] = {85,92,78,96,88}; | 5 ints set to given values |
| Auto-size | int scores[] = {85,92,78}; | Compiler counts — size = 3 |
| Partial init | int scores[5] = {85,92}; | First 2 set, remaining filled with 0 |
| Zero all | int scores[5] = {0}; | All 5 elements set to 0 |
int scores[5] = {85, 92, 78, 96, 88} — memory layout
#include <stdio.h> int main() { // Method 1: declare then assign one by one int ages[4]; ages[0] = 20; ages[1] = 25; ages[2] = 19; ages[3] = 30; // Method 2: declare and initialise together int scores[] = {85, 92, 78, 96, 88}; float prices[] = {9.99, 24.50, 4.75}; char grade[] = {'A', 'B', 'C', 'F'}; // Access individual elements by index printf("First score: %d\n", scores[0]); // 85 printf("Third score: %d\n", scores[2]); // 78 printf("Last score: %d\n", scores[4]); // 88 // Modify an element scores[2] = 95; printf("Updated [2]: %d\n", scores[2]); // 95 // sizeof trick to get number of elements int n = sizeof(scores) / sizeof(scores[0]); printf("Number of elements: %d\n", n); // 5 return 0; }
First score: 85 Third score: 78 Last score: 88 Updated [2]: 95 Number of elements: 5
scores[10] on a 5-element array gives no error — it silently reads or writes random memory. This is one of the most dangerous bugs in C. Always keep your index between 0 and n-1. Use sizeof(arr)/sizeof(arr[0]) to always get the correct count.
Array Operations — Loop, Sum, Min, Max
The real power of arrays comes when paired with loops. A for loop lets you process every element with the same code — whether there are 5 elements or 5000, the loop looks identical.
#include <stdio.h> int main() { int arr[] = {64, 25, 12, 92, 43, 37}; int n = sizeof(arr) / sizeof(arr[0]); // ── Print all elements ── printf("Array: "); for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); // ── Sum and average ── int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; printf("Sum: %d\n", sum); printf("Average: %.1f\n", (float)sum / n); // ── Find maximum ── int max = arr[0]; // assume first is max for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; printf("Maximum: %d\n", max); // ── Find minimum ── int min = arr[0]; // assume first is min for (int i = 1; i < n; i++) if (arr[i] < min) min = arr[i]; printf("Minimum: %d\n", min); // ── Reverse print ── printf("Reversed: "); for (int i = n - 1; i >= 0; i--) printf("%d ", arr[i]); printf("\n"); return 0; }
Array: 64 25 12 92 43 37 Sum: 273 Average: 45.5 Maximum: 92 Minimum: 12 Reversed: 37 43 92 12 25 64
#include <stdio.h> int main() { int n; printf("How many numbers? "); scanf("%d", &n); int arr[n]; // variable-length array (VLA) printf("Enter %d numbers:\n", n); for (int i = 0; i < n; i++) { printf(" [%d]: ", i); scanf("%d", &arr[i]); } printf("You entered: "); for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); return 0; }
Starting
max = 0 fails if all values are negative — max = arr[0] is always correct because it starts with an actual value from the array.
Sorting & Searching Arrays
Two of the most fundamental array algorithms. Linear search checks every element one by one. Bubble sort repeatedly compares adjacent elements and swaps them until sorted. These are the building blocks of everything more complex.
#include <stdio.h> int main() { int arr[] = {10, 35, 7, 42, 19, 88, 3}; int n = sizeof(arr) / sizeof(arr[0]); int target = 42; int found = -1; // -1 means not found yet for (int i = 0; i < n; i++) { if (arr[i] == target) { found = i; break; // no need to keep searching } } if (found != -1) printf("Found %d at index %d\n", target, found); else printf("%d not found in array\n", target); return 0; }
Found 42 at index 3
#include <stdio.h> void printArr(int arr[], int n) { for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); } int main() { int arr[] = {64, 25, 12, 92, 43}; int n = sizeof(arr) / sizeof(arr[0]); printf("Before: "); printArr(arr, n); // Bubble sort — n-1 passes for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } printf("After: "); printArr(arr, n); return 0; }
Before: 64 25 12 92 43 After: 12 25 43 64 92
2D Arrays — Rows & Columns
A 2D array is an array of arrays — a table with rows and columns. Declare with int mat[rows][cols]. Access each element with two indices: mat[row][col]. Traverse with nested loops — outer loop for rows, inner loop for columns.
- First index → row (0 = first row)
- Second index → column (0 = first column)
- Memory is stored row by row — row 0 all elements, then row 1, etc.
int mat[3][4] — 3 rows × 4 columns. mat[1][2] = 7
#include <stdio.h> int main() { // 3 rows, 4 columns int mat[3][4] = { {1, 2, 3, 4}, // row 0 {5, 6, 7, 8}, // row 1 {9, 10, 11, 12} // row 2 }; // Print matrix using nested loops printf("Matrix:\n"); for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) printf("%4d", mat[i][j]); printf("\n"); } // Sum of all elements int total = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) total += mat[i][j]; printf("Sum of all: %d\n", total); // Sum of each row for (int i = 0; i < 3; i++) { int rowSum = 0; for (int j = 0; j < 4; j++) rowSum += mat[i][j]; printf("Row %d sum: %d\n", i, rowSum); } return 0; }
Matrix: 1 2 3 4 5 6 7 8 9 10 11 12 Sum of all: 78 Row 0 sum: 10 Row 1 sum: 26 Row 2 sum: 42
#include <stdio.h> int main() { int a[2][2] = {{1,2},{3,4}}; int b[2][2] = {{5,6},{7,8}}; int c[2][2]; for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) c[i][j] = a[i][j] + b[i][j]; printf("A + B =\n"); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) printf("%4d", c[i][j]); printf("\n"); } return 0; }
A + B = 6 8 10 12
Passing Arrays to Functions
When you pass an array to a function, C passes the address of the first element automatically — not a copy. This means:
- The function can modify the original array directly
- No
&needed — array name is already an address - The function does NOT know the array size — always pass it as a second parameter
- Use
const int arr[]if the function should not modify the array
#include <stdio.h> // const = read-only — promise not to modify void printArray(const int arr[], int n) { for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); } int sumArray(const int arr[], int n) { int total = 0; for (int i = 0; i < n; i++) total += arr[i]; return total; } // No const — this function MODIFIES the original void doubleAll(int arr[], int n) { for (int i = 0; i < n; i++) arr[i] *= 2; // modifies original array! } void reverseArray(int arr[], int n) { for (int i = 0; i < n / 2; i++) { int temp = arr[i]; arr[i] = arr[n - 1 - i]; arr[n-1-i] = temp; } } int main() { int nums[] = {1, 2, 3, 4, 5}; int n = 5; printf("Original: "); printArray(nums, n); printf("Sum: %d\n", sumArray(nums, n)); doubleAll(nums, n); printf("Doubled: "); printArray(nums, n); reverseArray(nums, n); printf("Reversed: "); printArray(nums, n); return 0; }
Original: 1 2 3 4 5 Sum: 15 Doubled: 2 4 6 8 10 Reversed: 10 8 6 4 2
const when a function should not change the array.void print(const int arr[], int n) — the const keyword prevents the function from modifying the array. If it tries, the compiler throws an error. Always use const for read-only functions — it documents intent and prevents bugs.
Putting It All Together — Student Records
A complete student marks program using everything — arrays, loops, functions, sorting, and user input. Each function does one job. The program reads marks, finds statistics, sorts and displays results.
#include <stdio.h> void bubbleSort(int a[], int n) { for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (a[j] > a[j+1]) { int t=a[j]; a[j]=a[j+1]; a[j+1]=t; } } char grade(int m) { if(m>=90)return'A'; if(m>=75)return'B'; if(m>=50)return'C'; return 'F'; } int main() { int n; printf("Enter number of students: "); scanf("%d", &n); int marks[n]; for (int i = 0; i < n; i++) { printf(" Student %d marks: ", i+1); scanf("%d", &marks[i]); } // Stats before sorting int sum=0, max=marks[0], min=marks[0]; for (int i=0; i<n; i++) { sum += marks[i]; if(marks[i]>max) max=marks[i]; if(marks[i]<min) min=marks[i]; } printf("\n=== RESULTS ===\n"); printf("Average : %.1f\n", (float)sum/n); printf("Highest : %d (%c)\n", max, grade(max)); printf("Lowest : %d (%c)\n", min, grade(min)); bubbleSort(marks, n); printf("Sorted : "); for(int i=0;i<n;i++) printf("%d ",marks[i]); printf("\n"); return 0; }
Enter number of students: 5 Student 1 marks: 78 Student 2 marks: 92 Student 3 marks: 65 Student 4 marks: 88 Student 5 marks: 45 === RESULTS === Average : 73.6 Highest : 92 (B) Lowest : 45 (F) Sorted : 45 65 78 88 92
Quick Quiz
Given int arr[5] = {10,20,30,40,50}; — what is arr[3]?
What happens when you access arr[10] on an array of size 5?
How do you get the number of elements in int arr[] = {1,2,3,4,5}; safely?
When you pass an array to a function, the function receives:
Given int m[3][3] — how do you access row 2, column 1?
Lesson Checklist
- I know an array stores same-type values in contiguous memory
- I know array index starts at 0 — first is [0], last is [n-1]
- I can declare and initialise arrays both ways
- I use sizeof(arr)/sizeof(arr[0]) to get element count
- I know C does not check bounds — accessing out of range is undefined
- I can loop through an array to find sum, min, max, average
- I start max/min from arr[0] — not from 0
- I can implement linear search — find element by value
- I can implement bubble sort — sort array in ascending order
- I can declare and traverse a 2D array with nested loops
- I know arrays are passed by reference to functions — always
- I always pass the array size as a second parameter
- I use const when a function should not modify the array
- I completed the quiz
What to Learn Next
- 🧵 Strings — char arrays with special rules and string.h functions Next
- 📌 Pointers & arrays — arr[i] is *(arr+i) — same thing Next
- 📦 Dynamic arrays — malloc to create arrays at runtime Advanced
- 🏗️ Array of structs — store records of mixed types Advanced