C array search with explicit length
Search only within the supplied array bounds.
On this page
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
#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;
}2
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
#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;}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
| Step / line | What happens | State after step | Output 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.