C ProgrammingUnit 58 min read
Arrays & Multi-dimensional Arrays: Declaration, Traversal, Operations & Applications
Unit 5 of C Programming covers arrays (1D/2D), their declaration, initialization, traversal, and operations (sorting, searching, matrix arithmetic), with a focus on multi-dimensional arrays, pointer-array equivalence, and real-world applications in data storage and algorithms. Includes visual traces of operations and c
TAKEAWAYS:
- Arrays store homogeneous data in contiguous memory; declare as
type name[size]and access viaarray[index]. - Multi-dimensional arrays (e.g., matrices) are stored in row-major order; declare as
type name[rows][cols]. - Pointers and arrays are interchangeable in C (e.g.,
arrand&arr[0]point to the same address). - Common operations include traversal, sorting (bubble/selection), searching (linear/binary), and matrix arithmetic (addition, multiplication).
- Real-world use: Arrays model queues (Pathao order processing), matrices (NTC traffic route optimization), and lookup tables (NEPSE stock prices).
- Exam focus: Write programs for array traversal, matrix operations, and pointer-array equivalence with correct syntax and logic.
1. Arrays: Definition, Declaration, and Initialization
An array is a contiguous memory block storing elements of the same data type. It allows efficient access via indices (starting at 0 in C).
Declaration and Initialization
int marks[5]; // Uninitialized array (garbage values)
int scores[] = {85, 90, 78, 92, 88}; // Initialized array (size inferred)
float temps[3] = {23.5, 25.1, 22.8}; // Explicit size
Visual: Array in Memory
- Size: Fixed at compile-time (
sizeof(array)/sizeof(array[0])). - Indexing: Valid range
0tosize-1(accessing beyond causes undefined behavior).
Traversal Example: Sum of Array Elements
#include <stdio.h>
int main() {
int arr[] = {3, 7, 2, 8, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += arr[i];
}
printf("Sum: %d", sum); // Output: 25
return 0;
}
Step-by-Step Trace:
Iteration (i) |
arr[i] |
sum (cumulative) |
|---|---|---|
| 0 | 3 | 3 |
| 1 | 7 | 10 |
| 2 | 2 | 12 |
| 3 | 8 | 20 |
| 4 | 5 | 25 |
2. Multi-dimensional Arrays (Matrices)
A 2D array (matrix) is an array of arrays. Stored in row-major order (all rows stored sequentially).
Declaration and Initialization
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Visual: 2D Array in Memory
- Access:
matrix[row][col](e.g.,matrix[1][2]→6). - Size:
rows × cols(e.g.,2 × 3 = 6elements).
Matrix Addition Example
Problem: Add two 2×3 matrices.
#include <stdio.h>
int main() {
int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
int B[2][3] = {{6, 5, 4}, {3, 2, 1}};
int C[2][3];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
printf("Result:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
return 0;
}
Output:
9 7 7
7 7 7
Step-by-Step Trace for C[0][1]:
| Step | A[0][1] |
B[0][1] |
C[0][1] = A[0][1] + B[0][1] |
|---|---|---|---|
| 1 | 2 | 5 | 7 |
3. Arrays and Pointers: Key Similarities
Arrays and pointers are interchangeable in C because an array name decays to a pointer to its first element.
Comparison Table
| Feature | Array | Pointer |
|---|---|---|
| Declaration | int arr[5]; |
int *ptr; |
| Access | arr[i] |
*(ptr + i) |
| Address of first elem | &arr[0] or arr |
ptr |
| Modifiable? | No (size fixed) | Yes (can be reassigned) |
Example: Pointer Arithmetic
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40};
int *ptr = arr; // ptr points to arr[0]
printf("arr[1] = %d\n", arr[1]); // 20
printf("*(ptr + 1) = %d\n", *(ptr + 1)); // 20
printf("ptr + 2 = %p\n", ptr + 2); // Address of arr[2]
return 0;
}
Visual: Pointer Traversal
4. Common Array Operations
(a) Linear Search
int linearSearch(int arr[], int size, int key) {
for (int i = 0; i < size; i++) {
if (arr[i] == key) return i;
}
return -1;
}
Trace for arr = {5, 2, 9, 1}, key = 9:
i |
arr[i] |
Match? | Return |
|---|---|---|---|
| 0 | 5 | No | - |
| 1 | 2 | No | - |
| 2 | 9 | Yes | 2 |
(b) Bubble Sort
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
Visual: Bubble Sort Steps
5. Real-World Applications
(a) Pathao Order Queue
- Idea Used: Queue (array-based) to manage ride requests.
- How:
- Orders are stored in a FIFO (First-In-First-Out) array.
- New orders are added at the rear, and the next driver picks from the front.
- Example: If 3 orders arrive (
[O1, O2, O3]), the first driver getsO1, the secondO2, etc.
(b) NTC Traffic Route Optimization
- Idea Used: 2D Array (Adjacency Matrix) to represent roads and distances.
- How:
matrix[i][j]= distance between nodeiandj.- Algorithms like Dijkstra’s use this to find the shortest path.
- Example:
int distance[4][4] = { {0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0} };
(c) NEPSE Stock Price Lookup
- Idea Used: 1D Array for storing daily closing prices.
- How:
prices[day]stores the price for that day.- Example: Find the highest price in a week:
int prices[] = {1200, 1250, 1300, 1280, 1320, 1350, 1310}; int max = prices[0]; for (int i = 1; i < 7; i++) { if (prices[i] > max) max = prices[i]; } // max = 1350
6. Exam Tip
Syntax Matters:
- Always declare arrays with correct size (e.g.,
int arr[5]notint arr). - For multi-dimensional arrays, rows × cols must match (e.g.,
int mat[2][3]can’t hold 5 elements).
- Always declare arrays with correct size (e.g.,
Pointer-Array Trick:
- In exams, if asked to pass an array to a function, use:
void func(int arr[], int size) { ... } // or void func(int *arr, int size) { ... } - Never pass
sizeof(arr)directly (it decays tosizeof(int*)in the function).
- In exams, if asked to pass an array to a function, use:
Matrix Operations:
- For addition/multiplication, ensure compatible dimensions:
- Addition: Same rows × cols (e.g.,
2×3 + 2×3). - Multiplication: Columns of first × rows of second (e.g.,
2×3 × 3×4is valid).
- Addition: Same rows × cols (e.g.,
- For addition/multiplication, ensure compatible dimensions:
Traversal and Sorting:
- Always initialize loop counters (
i = 0,j = 0). - For sorting, trace one pass to show understanding (e.g., bubble sort swaps).
- Always initialize loop counters (
Common Pitfalls:
- Off-by-one errors:
for (int i = 0; i <= size; i++)→ wrong (use<). - Uninitialized arrays: Always initialize or use
scanfto avoid garbage values. - Pointer arithmetic:
ptr + imoves bysizeof(type)bytes (e.g.,int→ 4 bytes).
- Off-by-one errors:
Final Note: Practice writing functions that manipulate arrays (e.g., reverseArray, findMax). Use pointers to show deep understanding. For matrices, visualize row-major order to avoid confusion.
Based on the TU BIT syllabus for C Programming (BIT102), unit 5.
Discussion
Loading…