Suppose you need the marks of 60 students. Sixty separate variables (m1, m2... m60) would be painful. An array stores many values of the same type under one name, in consecutive memory locations.
Declaring and using an array#
int marks[5]; // 5 ints, indexes 0..4
int marks[5] = {78, 92, 65, 88, 71}; // declare + initialise
int primes[] = {2, 3, 5, 7, 11}; // size worked out automatically (5)
Elements are accessed with an index in square brackets. The first element is marks[0], the last is marks[4].
First: 78, Last: 71 marks[0] = 78 marks[1] = 92 marks[2] = 70 marks[3] = 88 marks[4] = 71 Total = 399, Average = 79.8
Array एक ही type के कई values को एक नाम से, memory में लगातार (एक के बाद एक) रखता है। गिनती 0 से शुरू होती है - 5 elements वाले array का आखिरी index 4 है। marks[5] लिखना array की सीमा से बाहर जाना है - C इसकी कोई error नहीं देता, पर program गलत या crash हो सकता है।
C does not check array bounds. Reading or writing marks[5] in a 5-element array touches memory that belongs to something else - a silent, dangerous bug. Always loop with i < n, never i <= n.
Reading an array from input#
3 of 6 numbers are even
Linear search#
Check each element one by one - works on any array:
131 found at index 3
Binary search (on a sorted array)#
If the array is sorted, look at the middle element: if the key is bigger, search the right half, otherwise the left half. Each step halves the range, so even 1,000,000 elements need only about 20 steps.
58 is at index 11 40 is at index -1
When you pass an array to a function, C passes the address of its first element, not a copy. So the function can modify the caller's array, and it cannot know the size - pass n separately.
Sorting: bubble sort#
Bubble sort repeatedly compares neighbours and swaps them if they are in the wrong order. After each pass, the largest remaining value "bubbles" to the end.
3 11 12 22 25 64 90
2D arrays (matrices)#
A 2D array is an array of rows. int m[3][4] has 3 rows and 4 columns; m[i][j] is row i, column j.
Sum matrix: 7 7 7 7 7 7
Matrix multiplication#
For C = A × B, element C[i][j] is the sum of A[i][k] × B[k][j] over k. The number of columns of A must equal the number of rows of B.
58 64 139 154
Summary#
- An array stores many same-type values; indexes run from
0tosize - 1. - Size =
sizeof(a) / sizeof(a[0]); C never checks bounds for you. - Arrays are passed to functions as addresses, so pass the length too.
- Linear search works anywhere; binary search needs a sorted array.
- 2D arrays:
m[row][col], processed with nested loops.