⚡0 XP🔥0

Arrays (1D and 2D)

Lesson 8 of 13 ⏱ 7 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs C

Store many values in one variable - declare and initialise arrays, loop over them, find max/min, search, sort, and work with 2D arrays (matrices).

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].

▶ Try it YourselfC
Ctrl + Enter to run
Output
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 हो सकता है।

Common Mistake

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#

▶ Try it YourselfC
Ctrl + Enter to run
Output
3 of 6 numbers are even

Check each element one by one - works on any array:

▶ Try it YourselfC
Ctrl + Enter to run
Output
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.

InteractiveBinary search, step by step

Type a number to find and press Search. Watch how the range (low...high) shrinks by half at every step.

▶ Try it YourselfC
Ctrl + Enter to run
Output
58 is at index 11
40 is at index -1
Note

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.

InteractiveWatch sorting algorithms work

Pick an algorithm and press Sort. Compare how many comparisons and swaps bubble, selection and insertion sort need for the same data.

▶ Try it YourselfC
Ctrl + Enter to run
Output
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.

▶ Try it YourselfC
Ctrl + Enter to run
Output
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.

▶ Try it YourselfC
Ctrl + Enter to run
Output
  58   64
 139  154

Summary#

  • An array stores many same-type values; indexes run from 0 to size - 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.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Max, min and average

Read n, then n integers into an array. Print the largest, smallest and average (2 decimals):

Max = 91
Min = 34
Average = 66.17
Test input:
6
56 91 34 78 67 71
Expected output:
Max = 91
Min = 34
Average = 66.17
2

Reverse an array in place

Read n and n integers, reverse the array in place (swap first with last, second with second-last...) and print it on one line separated by spaces.

Test input:
7
10 20 30 40 50 60 70
Expected output:
70 60 50 40 30 20 10
3

Matrix transpose

Read a 2×3 matrix and print its 3×2 transpose (rows become columns): one row per line, numbers separated by single spaces.

Test input:
1 2 3
4 5 6
Expected output:
1 4
2 5
3 6

Quick Quiz

Q1.

For int a[5]; what is the last valid index?

Q2.

What does int a[5] = {1, 2}; store?

Q3.

How do you find the number of elements in int a[] = {4, 8, 15, 16, 23, 42};?

Q4.

Binary search only works when the array is...

Q5.

For int m[3][4];, how many integers are stored?