Arrays in C: Storing Lists, Searching, Merging and Splitting

MODULE 3 • LESSON 07

Suppose a teacher wants a program that stores the marks of a class of 30 students, works out the average, and then lists everyone who scored above it. With only the variables you have used so far, you would need 30 separate declarations (mark1, mark2, … mark30) and 30 almost identical statements for every task. Worse, the program would have to be rewritten for a class of 31. An array solves all of this: one name for a whole list of values of the same type, with each value reached by its position.

Arrays and loops belong together. A loop counter becomes the position in the array, so a three-line loop can read, total, search or change every element, whatever the size of the list. In this lesson you will declare arrays, read data into them, output them, process them (totals, largest, counting, searching, changing values) and build new arrays by merging and splitting.

What you will learn

  • How to declare and initialise a one-dimensional array, and how indexes work.
  • How to read data into an array and output it with a for loop.
  • Why going outside the bounds of an array is dangerous, and how to avoid it.
  • How to process arrays: totals, averages, largest and smallest, counting and linear search.
  • How to modify the data in an array, and how to merge two arrays and split one array into two.
  • How parallel arrays can store simple records.

Part 1: Declaring arrays

int mark[30];
float price[5] = {2.5, 4.0, 1.75, 9.9, 3.2};
char grade[4] = {'A', 'B', 'C', 'F'};

A declaration gives the element type, the array name and, in square brackets, the number of elements (the size). The size must be a constant, so programs usually use #define N 30 and then int mark[N];. The elements sit next to each other in memory, which is what makes reaching any one of them fast.

Each element is reached with an index (or subscript) in square brackets. In C the first index is always 0, so int mark[30] has elements mark[0] to mark[29]. There is no mark[30]. The index can be any integer expression: mark[i], mark[i + 1], mark[n - 1]. Each element is used exactly like an ordinary variable: mark[3] = 75;, total += mark[i];, scanf("%d", &mark[i]);.

An array can be initialised with a list in braces. If the list is shorter than the array, the remaining elements are set to 0, so int count[10] = {0}; is a neat way to start ten counters at zero. If you give a list, you may leave the size out and let the compiler count: int days[] = {31, 28, 31}; has 3 elements. Without any initialiser, a local array holds garbage values, just like a local variable (Lesson 03).

Part 2: Reading and outputting arrays

The standard tool for working through an array is a for loop whose counter runs over every valid index: for (i = 0; i < N; i++). Start at 0, stop before N, step by 1. To work backwards, start at N − 1 and count down while i >= 0.

Worked example 1: read, display and reverse

The user typed the temperatures 31 29 33 30 28. The prompts show i + 1, because people count from 1 even though C counts from 0.

#include <stdio.h>

#define DAYS 5

int main(void)
{
    int temp[DAYS];
    int i;

    for (i = 0; i < DAYS; i++) {
        printf("Day %d: ", i + 1);
        scanf("%d", &temp[i]);
    }

    printf("\n%-5s%6s\n", "Day", "Temp");
    for (i = 0; i < DAYS; i++) {
        printf("%-5d%6d\n", i + 1, temp[i]);
    }

    printf("Reversed:");
    for (i = DAYS - 1; i >= 0; i--) {
        printf(" %d", temp[i]);
    }
    printf("\n");
    return 0;
}

Sample input: 31 29 33 30 28

Output:

Day 1: Day 2: Day 3: Day 4: Day 5: 
Day    Temp
1        31
2        29
3        33
4        30
5        28
Reversed: 28 30 33 29 31

Notice &temp[i] in scanf: an element of an int array is an int, so scanf needs its address, exactly as for any other int. The heading uses the same widths as the rows (Lesson 04).

Partly filled arrays

Often you do not know in advance how many values there will be: a teacher may enter marks until she types −1. The usual solution is to declare the array with the largest size you could ever need (say 40 for a class), and keep a separate counter n of how many elements are actually in use. The reading loop combines a sentinel with a bounds check, so that it stops at the sentinel or when the array is full: while (mark != -1 && n < 40). Inside the loop, store the value in marks[n] and then add 1 to n. Every later loop then runs from 0 to n − 1, never to 40, because the elements beyond n contain garbage.

Out of bounds. C does not check indexes. If a loop runs to i <= N, the last pass uses element N, which does not exist. The program reads or writes whatever happens to be in the next piece of memory. It may print a strange number, overwrite another variable or crash, and the error may only appear sometimes. This makes off-by-one errors with arrays especially serious. Try it below.

Try it 1Index explorer

The array is int a[8]. Set up the for loop and see which elements it visits: green is inside the array, red is outside it. The dashed boxes at [-1] and [8] are memory that does not belong to the array. Hit all five targets.

Start i =
Condition
End value
Update

    Part 3: Processing arrays

    Once data is in an array, the same handful of patterns answer most questions. Each is a loop over the indexes with one or two extra variables:

    TaskExtra variablesInside the loop
    Total and averagetotal = 0total += a[i]; then divide by N after the loop
    Largest (and where)best = 0 (an index)if (a[i] > a[best]) best = i;
    Count matching itemscount = 0if (a[i] > avg) count++;
    Linear searchpos = -1if (a[i] == target) pos = i; and stop when found
    Change every elementnonea[i] = a[i] + 5; (or * 1.1, and so on)
    Copya second arrayb[i] = a[i];

    Keeping the index of the largest value, rather than the value itself, tells you both what the largest is (a[best]) and where it is, which you often need (for example to print the name of the top student from a parallel array).

    A linear search checks each element in turn until it finds the target or runs out of elements. Using pos = −1 as “not found” works because −1 can never be a real index. The loop condition i < N && pos == -1 stops as soon as the item is found, so on average only half the array is checked. Searching a sorted array can be much faster with binary search, which you will meet in Unit 2.

    Worked example 2: analysing a list of marks

    #include <stdio.h>
    
    #define N 8
    
    int main(void)
    {
        int mark[N] = {56, 73, 88, 41,
                       73, 95, 62, 50};
        int i, total = 0, best = 0, above = 0;
        int target = 62, pos = -1;
        float avg;
    
        for (i = 0; i < N; i++) {
            total += mark[i];
            if (mark[i] > mark[best]) {
                best = i;
            }
        }
        avg = (float) total / N;
    
        for (i = 0; i < N; i++) {
            if (mark[i] > avg) {
                above++;
            }
        }
    
        i = 0;
        while (i < N && pos == -1) {
            if (mark[i] == target) {
                pos = i;
            }
            i++;
        }
    
        printf("Average: %.2f\n", avg);
        printf("Highest: %d at index %d\n",
               mark[best], best);
        printf("Above average: %d\n", above);
        if (pos >= 0) {
            printf("%d found at index %d\n",
                   target, pos);
        } else {
            printf("%d not found\n", target);
        }
        return 0;
    }
    

    Output:

    Average: 67.25
    Highest: 95 at index 5
    Above average: 4
    62 found at index 6

    Two loops are needed for “above average”: the first to find the average, the second to compare every mark with it. This is a typical reason to store data in an array rather than process each value as it is read: some tasks need to look at the data more than once.

    Part 4: Merging and splitting arrays

    Merging builds a new array from two (or more) others. The simplest merge copies all of the first array and then all of the second into a third array that is big enough for both. The key is a separate counter, k, for the next free position in the new array, because it keeps counting on from where the first copy stopped. If the order must change (for example, the elements of each array reversed), only the loops that read from the old arrays change; k still moves forwards through the new one.

    Splitting goes the other way: it works through one array and sends each element to one of two (or more) new arrays according to a condition, such as pass or fail, even or odd, or first half and second half. Each new array needs its own counter, which is both its next free position and, at the end, the number of elements it holds.

    Worked example 3: merge, then split

    This program uses a small function, show, to print an array with a label, because the same printing is needed five times. You will learn to write functions like this in Lesson 09; for now, read show(label, a, n) as “print n elements of a after the label”.

    #include <stdio.h>
    
    void show(char label[], int a[], int n)
    {
        int i;
        printf("%-6s", label);
        for (i = 0; i < n; i++) {
            printf("%4d", a[i]);
        }
        printf("\n");
    }
    
    int main(void)
    {
        int a[4] = {12, 7, 30, 5};
        int b[3] = {18, 9, 24};
        int c[7], even[7], odd[7];
        int i, k = 0, ne = 0, no = 0;
    
        for (i = 0; i < 4; i++) {
            c[k] = a[i];
            k++;
        }
        for (i = 0; i < 3; i++) {
            c[k] = b[i];
            k++;
        }
    
        for (i = 0; i < k; i++) {
            if (c[i] % 2 == 0) {
                even[ne] = c[i];
                ne++;
            } else {
                odd[no] = c[i];
                no++;
            }
        }
    
        show("A:", a, 4);
        show("B:", b, 3);
        show("C:", c, k);
        show("Even:", even, ne);
        show("Odd:", odd, no);
        return 0;
    }
    

    Output:

    A:      12   7  30   5
    B:      18   9  24
    C:      12   7  30   5  18   9  24
    Even:   12  30  18  24
    Odd:     7   5   9

    Notice that c, even and odd are all declared with 7 elements, the most they could ever need, but even and odd are only partly filled. The counters ne and no record how many elements are actually in use, and every later loop uses those counters, not 7, as its limit.

    Try it 2Array algorithm tracer

    Choose an algorithm and step through it. Array elements are shown as boxes with their index underneath; the element that has just changed has an orange border.

    Output

    
    

    Part 5: Parallel arrays, and what comes next

    Often each item has several pieces of data: a student has a name, an age and a mark. One way to store this is with parallel arrays: separate arrays where the same index refers to the same student, so name[3], age[3] and mark[3] all describe student 3. When you sort or swap, you must move the matching elements of every array together. Parallel arrays work, but they are easy to get out of step. In Lesson 11 you will meet struct, which groups the fields of each record together properly, and in Lesson 08 you will see that a name is itself an array of characters.

    C also has two-dimensional arrays, such as int seat[10][20]; for 10 rows of 20 seats, processed with nested loops. They follow the same rules, with one index for each dimension.

    Common array errors

    ErrorExampleCorrection
    Index out of boundsfor (i = 0; i <= N; i++)for (i = 0; i < N; i++)
    Starting at 1 and missing element 0for (i = 1; i < N; i++)Start at 0
    Missing address-of in scanfscanf("%d", mark[i]);scanf("%d", &mark[i]);
    Assigning a whole arrayb = a;Copy element by element in a loop
    Variable size in a declarationint a[n]; with n read at run timeUse a #define constant big enough for the data
    Total not initialisedint total;int total = 0;

    Try it 3Array practice

    Pick a mode. "Indexes" asks about elements of a given array. "After a loop" asks what a loop stores in an element.

    Summary

    IdeaRemember
    Declarationtype name[SIZE]; size is a constant; elements 0 to SIZE − 1.
    Loop over allfor (i = 0; i < N; i++)
    BoundsC does not check them; going outside is a serious run-time error.
    ProcessingTotal, largest (keep the index), count, linear search with pos = −1.
    MergeCopy each source in turn into a new array using a separate counter k.
    SplitSend each element to one of two arrays, each with its own counter.

    Review questions

    1. Declare an array to hold the rainfall (in mm, with decimals) for each day of a 31-day month.

    Show answer

    float rain[31]; (or double rain[31];)

    2. Given int v[6] = {4, 9, 2, 7, 5, 1}; what are v[0], v[5] and v[2] + v[3]?

    Show answer

    v[0] = 4, v[5] = 1, v[2] + v[3] = 9.

    3. Write a for loop that reads 15 integers into an array called vals.

    Show answer

    for (j = 0; j < 15; j++) {
    scanf("%d", &vals[j]);
    }

    4. Explain what can happen if a program writes to a[10] when a was declared as int a[10].

    Show answer

    a[10] is outside the array (valid indexes are 0 to 9). C does not check, so the program overwrites whatever memory follows, which may corrupt another variable or crash the program.

    5. Write code to count how many elements of int t[N] are negative.

    Show answer

    neg = 0;
    for (i = 0; i < N; i++) {
    if (t[i] < 0) neg++;
    }

    6. Write code to add 5 bonus marks to every element of mark[N], without letting any mark exceed 100.

    Show answer

    for (i = 0; i < N; i++) {
    mark[i] += 5;
    if (mark[i] > 100) mark[i] = 100;
    }

    7. Explain why linear search uses -1 as the starting value of pos.

    Show answer

    -1 can never be a valid index, so if pos is still -1 after the loop, the item was not found.

    8. Describe how to merge arrays P (m elements) and Q (n elements) into R.

    Show answer

    Use a counter k = 0. Copy each element of P into R[k], adding 1 to k each time; then do the same for Q. R must have at least m + n elements, and k ends equal to m + n.

    Homework

    1. Write a program that reads 10 numbers into an array and prints the smallest, its position, and how many numbers are equal to it.
    2. Write a program that reads 8 marks and prints them in reverse order, then prints only those above the average.
    3. Write a fragment that merges arrays P (m elements) and Q (n elements) into R so that the elements of P appear in reverse order, followed by the elements of Q in reverse order. Declare everything you use.
    4. Split an array of 12 temperatures into two arrays: readings of 30 or more, and readings below 30. Print both with their counts.
    5. Use parallel arrays to store 5 product names (single letters will do for now) and prices; print the letter of the most expensive product.

    Mastery quiz: Arrays in C

    This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

    Mastery quiz: Arrays in C: Storing Lists, Searching, Merging and Splitting

    Your course badges: loading saved progress…

    View badges

      No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

      Saved in this browser on this device. Clearing browser data may remove your badges.

      Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

      1. Given int n[12]; what is the index of the last element?
      2. Which loop correctly stores a value in every element of int v[20]?
      3. Given int a[4] = {6, 2, 9, 4}; what is a[1] + a[3]?
      4. What does C do when a program uses an index outside the array?
      5. int c[5] = {1, 2}; What is c[4]?
      6. Which statement reads a value into element i of int m[10]?
      7. In a linear search, what does pos = -1 after the loop mean?
      8. When merging arrays A (3 elements) and B (4 elements) into C, C needs at least...
      9. When splitting an array into pass and fail arrays, each new array needs...
      10. Why is b = a; not a way to copy array a into array b?

      Exam tips

      Specimen Unit 1 Paper 01 (2021), Item 37. Choosing the loop that fills every element of an array. Check the first index (0), the last index (size − 1) and that the element, not the whole array, is on the left of the assignment.

      Specimen Unit 1 Paper 01 (2021), Item 34. Printing selected elements of an array with a while loop. List the values the index takes, then look each one up, remembering that the first element is index 0.

      Specimen Unit 1 Paper 02 (2021), Question 6(b). Merging two arrays into a third with the elements reversed, showing all declarations. Declare the new array big enough, use a separate counter for it, and count down through each source array. Homework question 3 is practice for this.

      CAPE 2024 Unit 1 Paper 02, Question 6(d). Writing a C function that processes an array. Lesson 09 shows how to pass an array and its size to a function; the processing loop is the same as in this lesson.

      More worked answers are on the CS Solutions page.

      Previous: Module 3 • Lesson 06 – Loops in C: for, while and do-while. Next: Module 3 • Lesson 08 – Strings in C: Working with Text in char Arrays.

      Syllabus link: CAPE Computer Science (CXC A19/U2/21), Programming (Unit 1, Module 3). Specific Objective 6: use arrays in programs (reading data into arrays, outputting data from arrays, manipulating and modifying array data, including merging and splitting). Character arrays (strings) follow in Lesson 08.

      Video search terms

      Search YouTube for: "C arrays tutorial for loop", "C linear search array", "merge two arrays in C".

      Try it 4Quick quiz

      Tap an answer. All eight questions are self-checks on this lesson.

      Updates

      2026/12/01

      - Updated the copyright line.

      2026/11/24

      - First version of the lesson.

      © 2026 islandclass.org

      Leave a Reply