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

  • Write a program for linear search in C.
  • Write a 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.
  • 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

/*
* C Program to search any element or number in an array
*/
#include <stdio.h>
#include <conio.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);
    
    /* Read array elements */
    for(counter = 0; counter < elementCount; counter++){
        scanf("%d", &inputArray[counter]);
    }
    
    printf("Enter a number to serach in Array\n");
    scanf("%d", &num);
    
    /* search num in inputArray from index 0 to elementCount-1 */
    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);
    }
         
    getch();
    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
Program to Rotate an Array by N Positions
C Program to Find Missing Number in Array
C Program to Move All Zeroes to the End of Array
C Program to Print Distinct Elements of Array
Program to Implement Two Stacks in an Array
C program to reverse an array
C Program to sort elements of an array in decreasing order
C Program to find count of each element of an array
C Program to print unique elements of an unsorted array
List of all array programs