Skip to lab content

UNIT 05 · Sorting and Searching

Linear search with a non-recursive function

EXERCISE 05AC173 sample runs

THE SYLLABUS QUESTION

What you need to solve

Write a C program that uses a non-recursive function to search for a Key value in a given list of integers using linear search method.
Input format & conventions

Array size n (1–100), then n integers (-1,000,000 to 1,000,000), then the key. The list need not be sorted. Output is the first 1-based position, or -1.

UNDERSTAND THE IDEA

Explanation

Linear search checks values one at a time from the beginning. It works on either sorted or unsorted input.

The non-recursive function returns a zero-based index on the first match and -1 otherwise. main converts an index into a 1-based position for display.

PLAN BEFORE CODING

Algorithm

  1. Read the array and key.
  2. Call linearSearch.
  3. Compare each element with the key.
  4. Return its index immediately on a match, or -1 after the loop.
  5. Display the first matching position or -1.

SEE THE CONTROL FLOW

Flowchart

Follow the arrows from Start. Diamonds ask a question; labeled arrows show the answer. A returning arrow repeats a loop. Function internals are grouped where needed; later input checks follow the rules in the program.

Flowchart for Linear search with a non-recursive function: input, decisions, processing, output and loop paths

On a phone, scroll sideways to read the diagram at full size. Open full-size flowchart ↗

C17

Complete C program

Download .c
#include <stdio.h>
#define MAX_SIZE 100

int readArray(int a[], int *n) {
    if (scanf("%d", n) != 1 || *n < 1 || *n > MAX_SIZE) return 0;
    for (int i = 0; i < *n; ++i)
        if (scanf("%d", &a[i]) != 1 || a[i] < -1000000 || a[i] > 1000000) return 0;
    return 1;
}

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

int main(void) {
    int a[MAX_SIZE], n, key;
    if (!readArray(a, &n) || scanf("%d", &key) != 1) {
        puts("Invalid input."); return 1;
    }
    int index = linearSearch(a, n, key);
    printf("Position: %d\n", index < 0 ? -1 : index + 1);
    return 0;
}
Open in compiler ↗

Code loads into the existing compiler. Enter the sample input there; sign-in and execution rules stay the same.

Compile and run locally
gcc -std=c17 linear-search.c -o lab
./lab

On Windows, run .\lab.exe after compiling with GCC. The interest program requires the math library where applicable.

FOLLOW THE VALUES

Dry run

Step / stateOperationResult
Array 7,2,9,2; key 2Check index 0: 7No match
Check index 1: 2MatchReturn index 1
Display index + 1First matching position2

CHECK THE BEHAVIOR

Sample input & output

Each output below was produced by compiling and running this exact program. Input values are entered in the stated order; the examples do not print input prompts.

Sample 1

INPUT
4
7 2 9 2
2
OUTPUT
Position: 2

Sample 2

INPUT
3
1 2 3
8
OUTPUT
Position: -1

Sample 3

INPUT
1
-4
-4
OUTPUT
Position: 1

Common mistakes

  • Unsorted input is allowed; do not accidentally apply binary-search assumptions.
  • Return -1 only after all possible elements have been checked.

WHY THIS GROWTH RATE?

Time and space complexity

Time O(n) worst case; O(1) additional search space.

Let n be the number of array elements. The search function checks values one at a time. If the key is missing or only at the end, it performs n comparisons, giving worst-case O(n) search time. If the first element matches, the search itself is O(1).

The complete program must first read all n elements, so its time remains O(n) even when the search finds the first value. The array uses O(n) input storage; the non-recursive search function uses only a loop index, giving O(1) additional search space.

Big-O describes how work grows as the stated input quantity grows; fixed factors and lower-order terms are omitted. The analysis treats fixed-width arithmetic as constant cost and the published limits as practical safety bounds.

PREPARE FOR YOUR LAB VIVA

Related viva questions & answers

6 focused questions

Try answering aloud, then expand the answer to check your reasoning. These questions focus on the concepts used in this program.

Why can linear search work on an unsorted list?

It examines elements individually and does not discard a region based on ordering. The key can be detected at any position regardless of whether nearby values are larger or smaller.

Which occurrence is returned if the key appears several times?

This function returns as soon as its forward scan finds a match. Therefore it returns the first occurrence's index, which the main function converts to a displayed position.

What does returning -1 from the linear-search function mean?

It means every allowed element was checked without finding the key. Valid array indexes are nonnegative, so -1 cannot be mistaken for a successful result.

Why must the loop use i < n rather than i <= n?

A list of n elements occupies indexes 0 through n - 1. Testing index n would read beyond the logical list and could access storage that is not valid for this search.

What are the best and worst cases for this linear search?

A match at the first element needs one comparison, giving O(1). An absent key or a first match at the last element needs n comparisons, giving O(n).

Why is this search function non-recursive?

It advances through the elements with a loop and never calls itself. The current index is enough to record progress, so no recursive call stack is needed.