In this source code example, we will write a code to implement the Sequential Search algorithm in the C programming language.
In this C program, we will take input from the User or console.
Sequential Search in C Programming
#include<stdio.h>
int sequential_search(int[], int, int);
void main() {
int x[20], i, n, p, key;
printf("\n Enter the number of element:");
scanf("%d", &n);
printf("\n Enter %d elements:", n);
for (i = 0; i < n; i++)
scanf("%d", &x[i]);
printf("\n Enter the element to be search:");
scanf("%d", &key);
p = sequential_search(x, n, key);
if (p == -1)
printf("\n The search is unsuccessful:\n");
else
printf("\n%d is found at location %d", key, p);
}
int sequential_search(int a[], int n, int k) {
int i;
for (i = 0; i < n; i++) {
if (k == a[i])
return (i);
}
return (-1);
}
Output:
Enter the number of element:
7
Enter 7 elements:10
20
30
40
50
70
60
Enter the element to be search:50
50 is found at location 4
Comments
Post a Comment