Here is the C program to search an element in array using linear search.
Required Knowledge
Algorithm to search an element in an unsorted array using linear search
Let inputArray is an integer array having N elements and K be the number to search.
Let inputArray is an integer array having N elements and K be the number to search.
- Using a for loop, we will traverse inputArray from index 0 to N-1.
- For every element inputArray[i], we will compare it with K for equality. If equal we will print the index of in inputArray.
C program to search an element in an array using linear search
#include <stdio.h> int main(){ int inputArray[100], elementCount, counter, num; printf("Enter Number of Elements in Array\n"); scanf("%d", &elementCount); printf("Enter %d numbers \n", elementCount); for(counter = 0; counter < elementCount; counter++){ scanf("%d", &inputArray[counter]); } printf("Enter a number to serach in Array\n"); scanf("%d", &num); for(counter = 0; counter < elementCount; counter++){ if(inputArray[counter] == num){ printf("Number %d found at index %d\n", num, counter); break; } } if(counter == elementCount){ printf("Number %d Not Present in Input Array\n", num); } return 0; }Output
Enter Number of Elements in Array 6 Enter 6 numbers 7 2 9 4 1 6 Enter a number to serach in Array 4 Number 4 found at index 3
Related Topics