C Programming · December 3, 2026

Passing Arrays to Functions in C: Search, Sum and Sort

Module II · Functions · Passing Arrays to Functions


🎯 Why Pass Arrays to Functions?

A teacher keeps the marks of 60 students. She wants one routine to find the total, another to find the topper and another to sort the list. Writing the same loops again and again inside main() would be messy. A far better plan is to write each job once as a function and hand it the whole list.

To work on a whole array, a function needs two things: the array itself and the number of elements in it. This lecture shows how to pass them, why the function can change the original array, and how to build small modular programs for sum, search, maximum, sorting and more.

main() owns the array
4562789055
[0][1][2][3][4]
⬇ array + size 5
arraySum(arr, n) adds the elements: sum = 330
⬇ returns 330
main(): total = 330

Figure 1: The caller hands over the array and its size. The function does the work and returns a result.

1️⃣ Passing a Single Element

Start with the simplest case. An element such as marks[1] is just an ordinary int. Passing it follows the call by value rule you learned in the previous lecture.

Program 1: Passing one array element

#include <stdio.h>

void tryToChange(int n);

int main(void) {
    int marks[3] = {50, 60, 70};
    tryToChange(marks[1]);
    printf("marks[1] is still %d\n", marks[1]);
    return 0;
}

void tryToChange(int n) {
    n = 999;
    printf("Inside: n = %d\n", n);
}
🖥️ Output:
Inside: n = 999
marks[1] is still 60
  • marks[1] holds 60. The call copies that value into the formal parameter n.
  • The function sets its copy to 999, but the array element stays 60.
  • So a single element is passed by value, like any other variable.

2️⃣ Passing the Whole Array

To pass the entire array, write only its name in the call, with no brackets and no index. In the function, declare the parameter with empty square brackets.

int arraySum(int arr[], int n);   /* prototype */
total = arraySum(marks, 5);       /* call: name of the array and its size */
📌 An array parameter is written int arr[]. The size goes in a second parameter such as int n, because the function cannot find the length by itself.

Program 2: Sum and average of an array

#include <stdio.h>

int arraySum(int arr[], int n);

int main(void) {
    int marks[5] = {45, 62, 78, 90, 55};
    int total = arraySum(marks, 5);
    printf("Total = %d\n", total);
    printf("Average = %.1f\n", total / 5.0);
    return 0;
}

int arraySum(int arr[], int n) {
    int i, sum = 0;
    for (i = 0; i < n; i++) {
        sum = sum + arr[i];
    }
    return sum;
}
🖥️ Output:
Total = 330
Average = 66.0
  • arraySum(marks, 5) passes the array name marks and the count 5.
  • The loop adds every element: 45 + 62 + 78 + 90 + 55 = 330.
  • The function returns the total. main() stores it and prints the average as 330 / 5.0 = 66.0.
  • The same function works for an array of any length. Just change the second argument.

3️⃣ The Big Difference: The Function Can Change the Original

Here is the surprise. A single int is copied, but an array is not. When you pass an array name, C passes the address of the first element, not a copy of all the elements. So the function works on the very same memory as main().

Program 3: A function that doubles every element

#include <stdio.h>

void doubleAll(int arr[], int n);
void printArray(int arr[], int n);

int main(void) {
    int data[4] = {3, 8, 5, 10};
    printf("Before: ");
    printArray(data, 4);
    doubleAll(data, 4);
    printf("After:  ");
    printArray(data, 4);
    return 0;
}

void doubleAll(int arr[], int n) {
    int i;
    for (i = 0; i < n; i++) {
        arr[i] = arr[i] * 2;
    }
}

void printArray(int arr[], int n) {
    int i;
    for (i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}
🖥️ Output:
Before: 3 8 5 10
After: 6 16 10 20
  • doubleAll is a void function. It returns nothing.
  • Yet after the call, data in main() holds 6, 16, 10, 20. The function changed the original array.
  • Compare this with Program 1, where a single element could not be changed. An array name passes where the array lives, so changes stick.
main(): int data[4]
3→68→165→1010→20
[0][1][2][3]
▲   same boxes   ▲
doubleAll(): arr holds the address of data[0]
arr = address of data[0]

Figure 2: The function receives the address of the first element, so arr[i] is the same memory as data[i].

💡 Remember: Single variables and single elements are passed by value (a copy). A whole array is passed by its address, so the function works on the original data.
Passing marks[1]Passing marks
What is sentA copy of one valueThe address of the first element
Can the function change the original?NoYes
Parameter in the functionint nint arr[]
Size needed as a separate argument?NoYes

4️⃣ Why the Size Must Be Passed Separately

Inside the function, arr only knows where the array starts. It has no idea where the array ends. Because of this, sizeof(arr) inside a function does not give the array size: it measures a pointer, not the array.

So main() works out the number of elements, where the array is declared, and sends it along. A handy formula is:

int n = sizeof(roll) / sizeof(roll[0]);   /* total bytes / bytes of one element */
⚠️ Warning: If you pass the wrong size, the loop will run past the end of the array and read or write memory that is not yours. C does not stop you. Always pass the correct count.

5️⃣ Searching: Linear Search as a Function

Program 4: Linear search that returns the index

#include <stdio.h>

int linearSearch(int arr[], int n, int key);

int main(void) {
    int roll[6] = {101, 105, 110, 120, 125, 130};
    int n = sizeof(roll) / sizeof(roll[0]);
    int pos = linearSearch(roll, n, 120);
    if (pos != -1)
        printf("Found 120 at index %d\n", pos);
    else
        printf("120 not found\n");
    pos = linearSearch(roll, n, 111);
    if (pos != -1)
        printf("Found 111 at index %d\n", pos);
    else
        printf("111 not found\n");
    return 0;
}

int linearSearch(int arr[], int n, int key) {
    int i;
    for (i = 0; i < n; i++) {
        if (arr[i] == key)
            return i;
    }
    return -1;
}
🖥️ Output:
Found 120 at index 3
111 not found
  • main() calculates n with sizeof and passes the array, its size and the key.
  • The loop checks each element. On a match, return i; leaves the function at once with the index.
  • If the loop finishes with no match, the function returns -1, a value that can never be a real index.
  • main() tests the result: -1 means “not found”.

Trace for key = 120:

iarr[i]arr[i] == 120 ?Action
0101NoContinue
1105NoContinue
2110NoContinue
3120Yesreturn 3;

6️⃣ Maximum and Minimum

Program 5: Highest and lowest temperature

#include <stdio.h>

int findMax(int arr[], int n);
int findMin(int arr[], int n);

int main(void) {
    int temp[7] = {31, 28, 35, 22, 40, 29, 33};
    printf("Highest = %d\n", findMax(temp, 7));
    printf("Lowest  = %d\n", findMin(temp, 7));
    return 0;
}

int findMax(int arr[], int n) {
    int i, max = arr[0];
    for (i = 1; i < n; i++) {
        if (arr[i] > max)
            max = arr[i];
    }
    return max;
}

int findMin(int arr[], int n) {
    int i, min = arr[0];
    for (i = 1; i < n; i++) {
        if (arr[i] < min)
            min = arr[i];
    }
    return min;
}
🖥️ Output:
Highest = 40
Lowest = 22
  • Both functions start by assuming the first element, arr[0], is the answer.
  • The loop starts at index 1 and replaces the answer whenever a better element appears.
  • Neither function changes the array. They only read it and return one value.

7️⃣ Sorting: Bubble Sort as a Function

Sorting is the perfect example of why a function must be able to change the original array. The sort rearranges the elements in place, and main() sees the sorted list afterwards, with nothing returned.

Program 6: Bubble sort and a print helper

#include <stdio.h>

void bubbleSort(int arr[], int n);
void printArray(int arr[], int n);

int main(void) {
    int a[6] = {64, 25, 12, 22, 11, 90};
    printf("Unsorted: ");
    printArray(a, 6);
    bubbleSort(a, 6);
    printf("Sorted:   ");
    printArray(a, 6);
    return 0;
}

void bubbleSort(int arr[], int n) {
    int i, j, temp;
    for (i = 0; i < n - 1; i++) {
        for (j = 0; j < n - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

void printArray(int arr[], int n) {
    int i;
    for (i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}
🖥️ Output:
Unsorted: 64 25 12 22 11 90
Sorted: 11 12 22 25 64 90
  • Each pass of the outer loop compares neighbours and swaps them if they are in the wrong order. The largest remaining element “bubbles” to the end.
  • j < n - 1 - i stops each pass earlier, because the last i elements are already in place.
  • The swap works here because it swaps array elements through the array’s address. It is not a swap of copies, like the one that failed in the last lecture.
  • printArray is a small helper reused before and after sorting. This is the modular style.

Trace of the first pass on {64, 25, 12, 22, 11, 90}:

jCompareSwap?Array after the step
064 > 25Yes25 64 12 22 11 90
164 > 12Yes25 12 64 22 11 90
264 > 22Yes25 12 22 64 11 90
364 > 11Yes25 12 22 11 64 90
464 > 90No25 12 22 11 64 90
Start:642512221190
Pass 1:251222116490
Pass 2:122211256490
Pass 3:121122256490
Pass 4:111222256490
Pass 5:111222256490

Figure 3: Green boxes are in their final place after each pass. Blue boxes are still being compared.

8️⃣ Reversing an Array In Place

Program 7: Reverse an array

#include <stdio.h>

void reverseArray(int arr[], int n);
void printArray(int arr[], int n);

int main(void) {
    int a[5] = {1, 2, 3, 4, 5};
    reverseArray(a, 5);
    printArray(a, 5);
    return 0;
}

void reverseArray(int arr[], int n) {
    int i, temp;
    for (i = 0; i < n / 2; i++) {
        temp = arr[i];
        arr[i] = arr[n - 1 - i];
        arr[n - 1 - i] = temp;
    }
}

void printArray(int arr[], int n) {
    int i;
    for (i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}
🖥️ Output:
5 4 3 2 1
  • The loop runs only n / 2 times. Each round swaps the element at position i with its mirror at n - 1 - i.
  • For 5 elements, the pairs are (0, 4) and (1, 3). The middle element, index 2, stays where it is.
  • Running the loop all the way to n would swap every pair twice and undo the reversal. That is a classic mistake.

9️⃣ Passing a Two-Dimensional Array

A 2-D array can be passed too, but there is one extra rule. The function must be told the number of columns in the parameter declaration. The number of rows can be left out and passed separately.

Program 8: Sum of all elements of a matrix

#include <stdio.h>

int matrixSum(int m[][3], int rows);

int main(void) {
    int table[2][3] = {{1, 2, 3}, {4, 5, 6}};
    printf("Sum of all elements = %d\n", matrixSum(table, 2));
    return 0;
}

int matrixSum(int m[][3], int rows) {
    int i, j, sum = 0;
    for (i = 0; i < rows; i++) {
        for (j = 0; j < 3; j++) {
            sum = sum + m[i][j];
        }
    }
    return sum;
}
🖥️ Output:
Sum of all elements = 21
  • int m[][3] says: an array of rows, where each row has exactly 3 integers.
  • The number of rows (2) is passed as the second argument.
  • The nested loops visit every element: 1+2+3+4+5+6 = 21.
In memory, rows are stored one after another (row-major order):
123456
[0][0][0][1][0][2][1][0][1][1][1][2]
To jump to the next row, C must know how many elements make one row.
That is why [3] (the column count) is required.

Figure 4: A 2-D array is laid out row by row, so the function needs the column count to find each element.

🔒 Protecting an Array with const

Some functions only need to read an array, such as one that counts or searches. Adding the word const to the parameter tells the compiler, and the reader, that the function must not change the elements.

Program 9: A read-only function using const

#include <stdio.h>

int countAbove(const int arr[], int n, int limit);

int main(void) {
    int marks[6] = {35, 72, 48, 90, 66, 81};
    printf("Students above 60: %d\n", countAbove(marks, 6, 60));
    return 0;
}

int countAbove(const int arr[], int n, int limit) {
    int i, count = 0;
    for (i = 0; i < n; i++) {
        if (arr[i] > limit)
            count++;
    }
    return count;
}
🖥️ Output:
Students above 60: 4
  • const int arr[] means the elements are read-only inside this function.
  • If you wrote arr[i] = 0; inside it, the compiler would report an error and stop you from damaging the data by accident.
  • Use const for every function that does not need to modify its array. It is good, safe practice.

🧭 Quick Guide: Element or Whole Array?

What do you want to pass?
One element ➜
f(marks[1])
by value
cannot change the original
Whole array ➜
f(marks, n)
by address
can change the original
pass the size too

Figure 5: Choose between passing one element and passing the whole array.

⚠️ Common Mistakes

MistakeWhy it is wrongFix
Calling arraySum(marks[], 5) or arraySum(marks[5], 5)Brackets in the call mean an element or a syntax errorWrite only the name: arraySum(marks, 5)
Using sizeof(arr) inside the function to get the lengthIt measures a pointer, not the arrayPass the size from main()
Passing the wrong sizeThe loop reads or writes outside the arrayPass the exact element count
Expecting an array to be copied like an intThe function gets the address, not a copyRemember that changes affect the original
Looping to n in a reverse functionEvery pair is swapped twiceLoop only n / 2 times
Leaving out the column count for a 2-D parameterC cannot locate elements without itint m[][3]
Forgetting const on a read-only functionIt could change data by accidentAdd const

❓ Frequently Asked Questions

Q1. Is an array passed by value or by reference?
C always passes by value, but the value of an array name is the address of its first element. That gives the effect of “by reference”: the function sees the original data.

Q2. Can a function return an array?
Not directly. A function can fill an array that main() passes in, as the examples above did. Returning arrays properly needs pointers, which come in the next lectures.

Q3. Is int arr[] the same as int *arr?
As a function parameter, yes. Both mean “the address of an int“. You will see the pointer form soon.

Q4. What if I want a function to work on a copy of the array?
Make a copy yourself first, with a loop, and pass the copy. Or use const to make sure the original is not changed.

✅ Key Takeaways

  • Passing one element, such as marks[1], is call by value: only a copy is sent.
  • Passing a whole array sends only its name, which stands for the address of the first element.
  • The function can therefore change the original array.
  • Declare the parameter as int arr[] and pass the size as a separate parameter.
  • Searching, summing, finding the maximum, sorting and reversing are natural array functions.
  • For 2-D arrays, the column count must appear in the parameter: int m[][3].
  • Use const on array parameters that must stay unchanged.
🎓 Practice questions: (1) Write float average(int arr[], int n) and test it on five marks. (2) Write a function that counts how many even numbers an array contains. (3) Write void copyArray(int from[], int to[], int n) and show that the second array becomes a copy. (4) Change linearSearch so it returns how many times the key appears. (5) Write a function that sorts an array in descending order and print the array before and after.
All 29 lessons in this series (open course page)

Part 1 · Getting Started

Part 2 · Data Types, Input/Output and Operators

Part 3 · Decisions and Loops

Part 4 · Arrays

Part 5 · Strings

Part 6 · Functions and Scope

Part 7 · Pointers