Beginner Array Problems C

Linear Search Program in C with Output

Search for a value in an integer array in C by checking each element in order, and print where it is found or that it is not found.

  • TimeO(n) worst and average case, O(1) best case
  • SpaceO(1)
  • Hints3
  • Read3 min
Quick answer

Linear search in C loops through the array from index 0 to n - 1 and compares each element with the key. When arr[i] == key, it returns i at once. If the loop ends with no match, it returns -1, and the caller prints "not found". It works on unsorted arrays, takes O(n) time in the worst case and O(1) extra space.

Linear searchArrays and for loopsReturning -1 for not foundFlag variables and break
1

Problem statement

Write a linear search program in C. Given an array and a key, find the index of the first element equal to the key. Print the index if it is found, or a "not found" message if it is not.

The array does not need to be sorted.

Input

An integer n, then n integers, then the key to search for.

Output

"<key> found at index <i>" or "<key> not found".

Examples

Example 1
Inputarr = {23, 8, 41, 16, 37}, key = 16
Output16 found at index 3

Index 0 is 23, 1 is 8, 2 is 41, 3 is 16.

Example 2
Inputarr = {23, 8, 41, 16, 37}, key = 50
Output50 not found

All five elements are compared and none equals 50.

Constraints

  • 1 <= n <= 100
  • Elements can be in any order and can repeat
2

Think before you code

Reveal the questions to ask yourself first
  • Can you stop the loop as soon as you find the key?
  • At what point can you be sure the key is not in the array?
  • What value can you return for "not found" that can never be a real index?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Loop with for (i = 0; i < n; i++) and compare arr[i] == key.
2 Hint 2
Return i as soon as it matches.
3 Hint 3
Put return -1 after the loop, not in an else inside it.
4

Approach

Reveal the step-by-step approach

Linear search algorithm

  1. For each index i from 0 to n - 1:
  2. If arr[i] == key, return i.
  3. After the loop, return -1.

Array indexes start at 0, so -1 can never be a real position. The caller checks for -1 to decide which message to print.

Case Comparisons for n elements
Best: key at index 0 1
Worst: key last or missing n
Average, key present about n / 2

Two ways to write it

  • Function returning an index: clean, reusable, and easy to test. This is the main solution below.
  • Flag variable in main: set found = 1 and break when the key matches, then check found after the loop. Many lab manuals use this version.

If the array is sorted, binary search finds the key with far fewer comparisons. See binary search in Java for that method.

5

Dry run

Walk through the example step by step

arr = {23, 8, 41, 16, 37}, key = 16:

i | arr[i] | arr[i] == 16?
--+--------+--------------
0 | 23     | no
1 | 8      | no
2 | 41     | no
3 | 16     | yes, return 3

For key = 50, all five rows say "no", the loop ends, and the function returns -1.

6

Solution

Reveal the full C solution
solution.c
#include <stdio.h>

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

int main(void) {
    int arr[] = {23, 8, 41, 16, 37};
    int n = sizeof(arr) / sizeof(arr[0]);
    int keys[] = {16, 23, 50};

    for (int k = 0; k < 3; k++) {
        int index = linear_search(arr, n, keys[k]);
        if (index != -1) {
            printf("%d found at index %d\n", keys[k], index);
        } else {
            printf("%d not found\n", keys[k]);
        }
    }
    return 0;
}

Output:

16 found at index 3
23 found at index 0
50 not found

23 is found on the first comparison, the best case. 50 needs all five comparisons, the worst case.

Search element in array in C with user input

This is the flag-and-break version. It prints a 1-based position, because users count from 1.

#include <stdio.h>

int main(void) {
    int n, key, arr[100];
    int found = 0;

    printf("Enter number of elements: ");
    scanf("%d", &n);
    printf("Enter %d numbers: ", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    printf("Enter element to search: ");
    scanf("%d", &key);

    for (int i = 0; i < n; i++) {
        if (arr[i] == key) {
            printf("%d found at position %d\n", key, i + 1);
            found = 1;
            break;
        }
    }
    if (!found) {
        printf("%d not found in the array\n", key);
    }
    return 0;
}
Enter number of elements: 5
Enter 5 numbers: 10 25 30 45 50
Enter element to search: 45
45 found at position 4
Enter number of elements: 5
Enter 5 numbers: 10 25 30 45 50
Enter element to search: 35
35 not found in the array
  • break stops the loop after the first match, so later elements are not checked.
  • The "not found" message is printed once, after the loop, only when found is still 0.

Find all occurrences

Remove the early exit to report every index where the key appears.

#include <stdio.h>

int main(void) {
    int arr[] = {4, 7, 4, 9, 4, 2};
    int n = 6, key = 4, count = 0;

    printf("%d found at index: ", key);
    for (int i = 0; i < n; i++) {
        if (arr[i] == key) {
            printf("%d ", i);
            count++;
        }
    }
    printf("\nTotal occurrences: %d\n", count);
    return 0;
}
4 found at index: 0 2 4
Total occurrences: 3

This version always checks all n elements, because it cannot know whether another match is still ahead.

The Python version is on linear search program in Python and the Java version on linear search in Java. To sort an array first, see selection sort program in C.

TimeO(n) worst and average case, O(1) best case
SpaceO(1)
7

Review before the interview

Common mistakes

  • Writing else return -1; inside the loop, so only the first element is ever checked.
  • Printing "not found" inside the loop, once for every element that does not match.
  • Using = instead of == in the if condition, which assigns the key and is almost always true.
  • Looping with i <= n, which reads one element past the end of the array.
  • Forgetting break in the flag version, so a duplicate key prints "found" more than once.

Edge cases to test

  • Key at index 0: found with one comparison.
  • Key at the last index: found, but only after n comparisons.
  • Duplicates: the basic version returns the first index only.
  • n = 0: the loop does not run and the function returns -1.

Interview follow-ups

  • How would you return the last index of the key instead of the first?
  • How would you write linear search using recursion?
  • What is a sentinel linear search, and how does it save one comparison per step?

Keep practising

Building your programming basics?

CodeBegun’s programs build problem-solving with mentor review and mock interviews, online or in Madhapur, Hyderabad.

Chat with us