Linear search C program

It’s a linear search C program that inputs numbers from the user, and stores these numbers in an array, then using the linear search algorithm to find the search number entered by the user, and print result on the screen.

To understand this program, it’s better you should know the following topics:

Program (1): to demonstrate linear search in C programming.

#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],i,t,n,k,p,flag=0;
printf("Enter the number of elements(upto 100) to be entered in the list : ",n);
scanf("%d",&n);
//accepting values into array
for(i=0;i<n;i++)
{
printf("Enter %d element : ",i+1);
scanf("%d",&a[i]);
}
printf("\n Enter the element to search:");
scanf("%d",&k);
//Searching process begin
for(i=0;i<n;i++)
{
if(a[i]==k)
{
p=i;
flag=1; // found at position
break;
}
}
//search result
if(flag==0)
printf("the element %d not found in the list",k);
else
printf("the element %d found at position %d",k,p+1);
getch();
}

Output (1)

Enter the number of elements(upto 100) to be entered in the list : 5
Enter 1 element : 2
Enter 2 element : 1
Enter 3 element : 5
Enter 4 element : 10
Enter 5 element : 12

Enter the element to search:10
the element 10 found at position 4

Published by

Electrical Workbook

We provide tutoring in Electrical Engineering.

Leave a Reply

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