Sequential Search using C

This example shows how Sequential Search algorithm works.

Simple way to search for a key value k in an array a is to compare the values of the elements in a with k. The process starts with the first element of the array and k and comparison continues as long as either the comparison does not result in a success or the list of elements in the array are exhausted. This method of searching is known as sequential search or linear search.

The following code example will return the index of the array when a successful search is found for the given key value and when the search is unsuccessful, the function returns -1.

The complete source code

/* 
 * File:   SequentialSearch.c
 * Author: https://www.roytuts.com
 */

#include <stdio.h>
#include <stdlib.h>

int sequentialSearch(int k, int a[], int n) {
    int i = 0;
    while (i < n) {
        if (k == a[i]) {
            break;
        } else {
            i++;
        }
    }
    if (i < n) {
        return i;
    } else {
        return -1;
    }
}

int main() {
    int choice, value;
    int a[] = {1, 8, 6, 9, 4, 5, 6};
    printf("\n:: Sequential Search ::\n");
    while (1) {
        printf("\nChoose from below Menu\n");
        printf("1. Search\n2. Exit\n");
        printf("\nEnter your choice: ");
        scanf("%d", &choice);
        switch (choice) {
            case 1: printf("Enter the value to be searched: ");
                scanf("%d", &value);
                int index = sequentialSearch(value, a, 7);
                if (index > 0) {
                    printf("\nValue found at index %d in the array\n", index);
                } else {
                    printf("\nValue not found in the array\n");
                }
                break;
            case 2: exit(0);
            default: printf("\nWrong selection!!! Please try again!!!\n");
        }
    }
}

Output

:: Sequential Search ::

Choose from below Menu
1. Search
2. Exit

Enter your choice: 1
Enter the value to be searched: 2

Value not found in the array

Choose from below Menu
1. Search
2. Exit

Enter your choice: 1
Enter the value to be searched: 5

Value found at index 5 in the array

Choose from below Menu
1. Search
2. Exit

Enter your choice: 2

Thanks for reading.

Soumitra Roy Sarkar

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *