# Sequential Search using C

This example shows how Sequential Search algorithm works. In sequential or linear search an element is searched or found in a list.

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.

## Time Complexity

Worst Complexity: O(n)
Average Complexity: O(n)
Space Complexity: O(1)
Worst-case Space Complexity: O(1) iterative

## Algorithm Implementation

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 given below in C programming language.

``````/*
* File:   SequentialSearch.c
* Author: https://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("1. Search\n2. Exit\n");
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 {
}
break;
case 2: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}``````

## Testing the Program

Executing the above C program will give you the following output:

``````:: Sequential Search ::

1. Search
2. Exit

Enter the value to be searched: 2

1. Search
2. Exit