C Program to Search an Element in an Array Using Linear Search

1. Introduction

Linear search, also known as a sequential search, is a method used to find a particular value in a list. It checks each element of the list sequentially until a match is found or the entire list has been searched. This is the simplest search algorithm and is often used to introduce the concept of algorithmic search.

2. Program Overview

In this program, we will:

1. Declare an array and initialize it with some values.

2. Take an input number from the user that we want to search in the array.

3. Use linear search to find the number in the array.

4. Print the result: either the index of the number (if found) or a message indicating it wasn't found.

3. Code Program

#include <stdio.h>

int main() {
    int arr[10] = {10, 23, 45, 67, 89, 90, 34, 56, 78, 12};
    int i, num, flag = 0;

    // Ask user for the number to be searched
    printf("Enter the number to search: ");
    scanf("%d", &num);

    // Linear search process
    for(i = 0; i < 10; i++) {
        if(arr[i] == num) {
            flag = 1;
            break;
        }
    }

    // Display the result
    if(flag == 1) {
        printf("Number %d found at index %d\n", num, i);
    } else {
        printf("Number %d not found in the array.\n", num);
    }

    return 0;
}

Output:

For input 45:
Number 45 found at index 2

For input 100:
Number 100 not found in the array.

4. Step By Step Explanation

1. We start by declaring and initializing an array arr with 10 integer values.

2. We then prompt the user to input the number they wish to search for.

3. Using a for loop, we perform the linear search by comparing each element of the array to the input number. If a match is found, we set the flag variable to 1 and break out of the loop.

4. After the loop, we check the value of the flag variable. If it's 1 (true), we print the index where the number was found. If it's 0 (false), we print a message indicating the number wasn't found in the array.

Comments