Function Assignment 21 — Search for an Element in an Array Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Search for an Element in an Array Using a Function

📑 On this page:
  • Linear search — the simplest search
  • Designing the linearSearch function
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How linear search works — checking elements one by one
  • Why returning an index (not a boolean) gives more information
  • How to use -1 as a sentinel value for "not found"
  • How early returns can short-circuit a search
  • When linear search is the right choice, and when to use binary search instead

Linear search — the simplest search

Linear search (also called sequential search) is the most straightforward way to find an element in an array. You look at each element in turn — index 0, then 1, then 2, and so on — and stop as soon as you find the one you're looking for. If you reach the end without finding it, the element isn't in the array. That's the whole algorithm.

It's not clever, but it has important virtues. It works on arrays of any kind — sorted, unsorted, or partially sorted. It doesn't require any preprocessing. It's easy to understand, easy to implement, and easy to prove correct. And for small arrays (a few hundred elements), it's perfectly fast. The slower-than-optimal asymptotic behavior only matters for large arrays where you're doing many searches — and in those cases, you'd sort the array once and use binary search.

There are two design choices worth thinking about. First, should the function return an index or a boolean? Returning an index is more informative — you know both whether the element exists and where it is. If you only returned a boolean, the caller would need to search again to find the location. Second, how do you signal "not found"? In C, the standard convention is to return -1, since valid indices are always non-negative. This is a common sentinel value and avoids using a separate output flag.

The function signature combines these choices: int linearSearch(const int arr[], int n, int target). It takes the array, its size, and the value to search for; it returns the index of the first match, or -1 if not found. This is the same shape as the standard memchr or strchr in the C library — both return a pointer to the found element, or NULL if absent.

💡 In one line: loop i from 0 to n-1. If arr[i] == target, return i. If the loop ends without a match, return -1. That's linear search.

An array with a magnifying glass walking left to right, examining each element until it finds the target.

Designing the linearSearch function

The signature has three parameters — the array, its size, and the target value:

Part Choice Why
Function namelinearSearchDistinguishes from other search algorithms (binary search, hashing). The name is a small but useful documentation.
Array parameterconst int arr[]Read-only. The function only inspects elements, never modifies them.
Size parameterint nRequired because arrays decay to pointers — the size can't be recovered.
Targetint targetThe value to look for. Same type as the array elements.
Return typeintIndex of the first match, or -1 if not found. Non-negative for valid indices, so -1 is unambiguous.

The prototype:

int linearSearch(const int arr[], int n, int target);
                                

And the definition:

int linearSearch(const int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) {
            return i;
        }
    }
    return -1;
}
                                

Eight lines of logic. The loop scans from 0 to n-1. On each iteration, it compares arr[i] to target. If they match, the function returns i immediately — no need to check the rest. If the loop reaches the end without finding a match, it returns -1.

The early return is the key optimization. If the target is at index 0, the function returns in one iteration — O(1). If the target isn't present, the function runs all n iterations — O(n). On average, for a random target, it does about n/2 iterations. This variable time complexity is a nice property: the function does work proportional to how far it needs to search.

A variant that returns a boolean (1 for found, 0 for not found), if you only need to know whether the element is present:

int contains(const int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) return 1;
    }
    return 0;
}
                                

Same loop, but returns 1 or 0 instead of an index. Use this when you only need a yes/no answer — for example, in a validation check ("is this value in the allowed list?"). But if there's any chance you'll need the index later, return the index upfront. Changing the function's return type later is more disruptive than using a richer return value from the start.

And a variant that finds the last occurrence instead of the first:

int linearSearchLast(const int arr[], int n, int target) {
    for (int i = n - 1; i >= 0; i--) {
        if (arr[i] == target) return i;
    }
    return -1;
}
                                

Scanning backwards from the end, this finds the last occurrence of the target. If you need all occurrences, return an array of indices instead of a single one — that's a different signature and a different function.

🎯 Key idea: return the index, not a boolean. An index tells you both existence and location; a boolean tells you only existence. Even if you currently only need "found or not," returning the index future-proofs the function against becoming richer later.

Complete C Program

Program: search for a target value in an array

#include <stdio.h>

/* Function prototype */
int linearSearch(const int arr[], int n, int target);

int main(void) {
    int arr[100];
    int n, target;

    printf("How many elements? ");
    if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
        printf("Please enter a valid count between 1 and 100.\n");
        return 1;
    }

    printf("Enter %d integers: ", n);
    for (int i = 0; i < n; i++) {
        if (scanf("%d", &arr[i]) != 1) return 1;
    }

    printf("Enter the value to search for: ");
    if (scanf("%d", &target) != 1) return 1;

    int idx = linearSearch(arr, n, target);
    if (idx == -1) {
        printf("%d was not found in the array.\n", target);
    } else {
        printf("%d found at index %d (position %d).\n", target, idx, idx + 1);
    }

    return 0;
}

/* Linear search — returns the index of the first match, or -1 */
int linearSearch(const int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) {
            return i;
        }
    }
    return -1;
}
                                    

A version that reports all occurrences of the target, not just the first:

Variant: find all occurrences

#include <stdio.h>

int searchAll(const int arr[], int n, int target, int indices[], int maxIndices) {
    int count = 0;
    for (int i = 0; i < n && count < maxIndices; i++) {
        if (arr[i] == target) {
            indices[count++] = i;
        }
    }
    return count;
}

int main(void) {
    int arr[100], n, target;
    printf("How many elements? ");
    if (scanf("%d", &n) != 1 || n <= 0) return 1;
    printf("Enter %d integers: ", n);
    for (int i = 0; i < n; i++) scanf("%d", &arr[i]);

    printf("Enter the value to search for: ");
    if (scanf("%d", &target) != 1) return 1;

    int indices[100];
    int count = searchAll(arr, n, target, indices, 100);

    if (count == 0) {
        printf("%d not found.\n", target);
    } else {
        printf("%d found at %d position(s): ", target, count);
        for (int i = 0; i < count; i++) {
            printf("%d ", indices[i]);
        }
        printf("\n");
    }
    return 0;
}
                                    

This variant collects all matches into an output array and returns the count. It's more complex but more informative — useful when you want to know all occurrences (e.g., all positions where a certain value appears in a larger dataset). The maxIndices parameter prevents overflow of the output array.

And a version that treats the array as sorted and uses binary search — much faster for large arrays, but requires sorting first:

Variant: binary search (requires sorted array)

#include <stdio.h>

int binarySearch(const int arr[], int n, int target) {
    int low = 0, high = n - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == target) return mid;
        if (arr[mid] < target) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

int main(void) {
    int arr[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 11;
    int idx = binarySearch(arr, n, target);
    if (idx == -1) printf("%d not found.\n", target);
    else printf("%d found at index %d\n", target, idx);
    return 0;
}
                                

Binary search is O(log n) — much faster than linear search's O(n) — but requires the array to be sorted. For an array of 1 million elements, linear search does up to 1 million comparisons; binary search does at most 20. That's a huge difference. The catch is that if you need to keep the array sorted (add/remove elements), maintenance costs can outweigh search savings. So binary search is right for static sorted data; linear search is right for small or unsorted arrays.

Program Output

A typical run with the target present:

How many elements? 5
Enter 5 integers: 10 20 30 40 50
Enter the value to search for: 30
30 found at index 2 (position 3).
                                

The index is 2 (0-based), so the position is 3 (1-based). Both numbers are shown, since different conventions apply to different contexts — programmers typically think in 0-based indices, users often think in 1-based positions.

With the target at the beginning:

How many elements? 5
Enter 5 integers: 10 20 30 40 50
Enter the value to search for: 10
10 found at index 0 (position 1).
                                

The target is at the very start, so the loop exits on the first iteration. This is the best case for linear search — O(1).

With the target at the end:

How many elements? 5
Enter 5 integers: 10 20 30 40 50
Enter the value to search for: 50
50 found at index 4 (position 5).
                                

The loop runs all 5 iterations — the worst case for finding. That's O(n).

With the target absent:

How many elements? 5
Enter 5 integers: 10 20 30 40 50
Enter the value to search for: 25
25 was not found in the array.
                                

The loop runs all 5 iterations without finding a match, then returns -1. The caller prints the "not found" message. This is another worst case — O(n).

With duplicates:

How many elements? 6
Enter 6 integers: 1 3 5 3 7 3
Enter the value to search for: 3
3 found at index 1 (position 2).
                                

There are three 3s (at indices 1, 3, and 5). The function returns the first match (index 1), because it returns as soon as it finds one. To find all occurrences, use the multi-occurrence variant.

And the binary search variant:

11 found at index 5
                                

In the sorted array {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}, 11 is at index 5. Binary search finds it in about 3 comparisons (the array's size is 10, log₂(10) ≈ 3.3), vs. linear search's 6. For a 1-million-element array, the difference would be ~20 comparisons vs. up to 1 million.

Step-by-Step Explanation

Let's trace the algorithm and look at the design choices.

1. The loop

for (int i = 0; i < n; i++) — scans every index from 0 to n-1. This is the standard linear iteration. On each iteration, we check one element.

2. The comparison

if (arr[i] == target) return i; — the equality check. If the element matches the target, we're done. Return the current index immediately.

The early return is essential. Without it, we'd continue scanning even after finding a match, wasting time. With it, we stop as soon as we find what we're looking for. On average, this cuts the work in half compared to scanning the entire array.

3. The "not found" case

return -1; — if the loop completes without ever hitting a match, then the target isn't in the array. We return -1 as a sentinel value. This works because valid array indices are 0 or greater — -1 unambiguously means "not found."

An alternative would be to return n (out of bounds) as the sentinel. That also works, but -1 is more idiomatic and less likely to collide with a real index (if you ever forget to bounds-check the array length, n could be confused with a valid index for an array of size n+1).

4. Tracing linearSearch({10, 20, 30, 40, 50}, 5, 30)

  1. i = 0: arr[0] = 10. 10 == 30? No. Continue.
  2. i = 1: arr[1] = 20. 20 == 30? No. Continue.
  3. i = 2: arr[2] = 30. 30 == 30? Yes! Return 2.
  4. Loop exits early. Return value: 2. ✓

Three iterations, then done. If we hadn't returned early, we'd have needed to check indices 3 and 4 as well. The early return saves work proportional to how early the target appears.

5. Tracing linearSearch({10, 20, 30, 40, 50}, 5, 25)

  1. i = 0: 10 != 25. Continue.
  2. i = 1: 20 != 25. Continue.
  3. i = 2: 30 != 25. Continue.
  4. i = 3: 40 != 25. Continue.
  5. i = 4: 50 != 25. Continue.
  6. Loop ends. Return -1.

Five iterations, no match. This is the worst-case time for linear search — O(n). You have to check every element to be sure the target isn't there.

6. Why return an index and not a boolean

If you only need to know whether the element exists, a boolean return would be simpler: int contains(...) returning 0 or 1. But an index is strictly more informative — it tells you both existence and location. If you have the index, you can check if (idx >= 0) to determine existence. So returning an index subsumes the boolean case, while also providing extra information that the caller might not need right now but might want later.

This is a general principle: return the richest useful answer, not the minimal answer. The "richer" return value rarely costs more (an index and a boolean are both int sized here), and it saves a redesign later.

7. Linear vs. binary search

Linear search is O(n) — for an array of size n, you might do n comparisons. Binary search is O(log n) — for the same array, at most log₂(n) comparisons. For n = 1,000,000, that's 1,000,000 vs. 20. Binary search is dramatically faster.

But binary search requires the array to be sorted. If the array is unsorted, you have two choices: sort first (O(n log n) time, then O(log n) per search), or just do linear search (O(n) per search). For a single search, linear search wins — sorting is more expensive than the one search. For many searches, sorting once and binary searching repeatedly pays off. This is a classic time-space tradeoff, and picking the right side depends on your usage pattern.

8. Complexity and the average case

Linear search has three cases:

  • Best case: target is at index 0 — 1 comparison, O(1).
  • Worst case: target is at index n-1, or not present — n comparisons, O(n).
  • Average case: target is randomly placed — about n/2 comparisons, still O(n) but with half the constant.

The asymptotic complexity is O(n) in the worst and average cases. For small arrays, this is negligible. For large arrays with many searches, other approaches become worthwhile.

9. Handling duplicates

If the target appears multiple times, our function returns the first occurrence (smallest index). This is a convention, not a requirement — you could return the last, or all, or any. Which you want depends on your use case. Our choice — first occurrence — is the most common convention and matches the behavior of strchr and similar library functions. Document it clearly in a comment or docstring.

10. Searching other types

The same algorithm works for arrays of any type — double, char, strings, structs. For strings, use strcmp instead of ==. For structs, define a comparison function that captures what "equal" means (comparing all fields? just the ID?). This is why the standard library has bsearch and qsort — they take a comparison function so the sort and search logic stays generic. Our simple == version is fine for primitive types; for composites, you'd generalize.

🔍 Try this: write a variant of linear search that returns the count of matches instead of the first index — it would scan the whole array, incrementing a counter for each match. Then write a "find all indices" function that fills an output array with every match. Each variant teaches something about what "search" can mean — find one, find all, count, find the last. They're all small twists on the same loop.

Frequently Asked Questions

1. Why return -1 for "not found" instead of NULL or n?

Because the return type is int, not a pointer. NULL is a pointer value, not an integer (well, NULL often expands to 0 for int in some contexts, but semantically it's a pointer concept). Using n (the array length) works too but is less idiomatic and risks confusion if you ever forget the bounds check. -1 is a widely recognized sentinel for "not found" — it's negative, so it can never be a valid index, and it's easy to check for. This is the standard convention and what the C library uses (via strchr returning NULL, or memchr similarly — the pointer analog of -1).

2. What if the target appears multiple times?

Our function returns the first occurrence (smallest index). To find the last, iterate backwards. To find all occurrences, return an array of indices and the count. Which behavior you want depends on your use case — usually, "first occurrence" is the natural default, but always document what your function does. A common convention is to return the first index; that's what the library strchr and memchr do.

3. When should I use linear search vs. binary search?

Use linear search when: the array is small (< ~1000 elements), the array is unsorted and will stay unsorted, or you're doing a single search (not worth the sort). Use binary search when: the array is sorted (or can be sorted once), you're doing many searches, and the array is large. Binary search is O(log n) vs. linear search's O(n) — huge difference for large data, but linear is simpler and doesn't require sorted input. For a "one-off" search on an arbitrary array, linear wins.

4. Can linear search work on a sorted array?

Yes — linear search works on any array, sorted or not. It just checks each element in order. Binary search is only correct on sorted arrays, but linear search is always correct. That's why linear search is the safer default: it doesn't require any preprocessing or assumptions about the input. If the array happens to be sorted, you can use binary search for a speedup, but linear search will still work (just slower).

5. Can I search for a value in a sorted array without a full scan?

Yes — that's exactly what binary search is for. It exploits the sorted order to eliminate half the array on each comparison, giving O(log n) time. The catch is that it requires the array to be sorted. If you're searching a sorted array many times, binary search is dramatically faster. But if you're searching an unsorted array even once, sorting first (O(n log n)) is slower than a single linear scan (O(n)). Choose based on your usage pattern — one search: linear. Many searches: sort once, binary search.

6. How does C's bsearch compare to my linearSearch?

bsearch (in <stdlib.h>) is a binary search that works on any type. It's more general (takes a comparison function), and much faster on sorted arrays, but has the same limitation — it requires sorted input. Also, it returns a void * (a pointer to the found element), not an index. Our linearSearch is simpler, works on unsorted arrays, and returns an index. For small arrays or unsorted data, use linearSearch; for large sorted arrays where performance matters, use bsearch (or a hand-rolled binary search like the variant shown).

💡 Tip: Once this works, implement binary search (which requires a sorted array). Then compare the performance for large arrays — the difference is dramatic (e.g., 1 million comparisons for linear search vs. ~20 for binary search on the same array). That exercise makes the O(n) vs. O(log n) distinction concrete. Then try a hash table (or a simpler option, an array used as a lookup table for small value ranges) — an even faster search for certain cases (O(1) on average), but with more memory overhead. Different search structures for different problems.

📖 Related Tutorials

  • Introduction to Functions in C
  • One Dimensional Arrays
  • Passing Arrays to Functions
  • Function Definition
  • Function Declaration
  • Previous: Calculate the Sum of Elements in an Array
  • Next: Sort Elements in an Array in Ascending Order
  • All 33 Function Assignments

Previous Topic: -->> 20. Calculate the Sum of Elements in an Array Using a Function   ||   Next Topic: -->> 22. Sort Elements in an Array in Ascending Order Using a Function


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.