C · Course navigation

C array search with explicit length

Search only within the supplied array bounds.

On this page
Before you start

Arrays, functions, and loops.

  • Search only within the supplied array bounds.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

An array parameter is adjusted to a pointer in a C function. The function does not automatically know how many elements are available, so length must be passed separately.

This search returns the first matching index or -1. The caller promises that n is nonnegative and no larger than the accessible element count.

Code example

C
#include <stdio.h>
#include <assert.h>
int find(const int values[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (values[i] == target) return i;
    }
    return -1;
}
int main(void) {
    int values[] = {5, 2, 7};
    printf("%d\n", find(values, 3, 7));
    assert(find(values, 0, 7) == -1);
    assert(find(values, 3, 9) == -1);
    return 0;
}
Output
2

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1#include <stdio.h>
2#include <assert.h>
3int find(const int values[], int n, int target) {
4 for (int i = 0; i < n; i++) {
5 if (values[i] == target) return i;
6 }
7 return -1;
8}
9int main(void) {
10 int values[] = {5, 2, 7};
11 printf("%d\n", find(values, 3, 7));
12 assert(find(values, 0, 7) == -1);
13 assert(find(values, 3, 9) == -1);
14 return 0;
15}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Create three elements.values = [5, 2, 7]
—
Index 0 does not match 7.i = 0, value = 5
—
Index 1 does not match.i = 1, value = 2
—
Index 2 matches; return it.return = 2
—
Print the found index.return = 2
2
Check zero-length and missing-target cases.return = 2
2

Behind the scenes

How C processes this code

The C compiler produces a native program. Variables occupy memory, and execution enters main.

Cost and common mistakes

O(n) worst-case time and O(1) auxiliary space.

  • Using sizeof on the pointer parameter does not recover the array length.
  • Passing a length larger than the actual array allows invalid reads.

Try it yourself

Search for 5 and then 4.

Reveal answer and reasoning

The results are 0 and -1 respectively.

Further reading