The below code will perform linear search on an array.Linear search has a time complexity of O(n).
Logic: In linear search each element of the array is checked for target element one by one.
Code:
#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,size,target,found;
size=10; //size of the array
int array[size];
//take input from user to fill the array
printf("Welcome\nEnter ten numbers:\n);
for(i=0;i<size;i++)
{
scanf("%d,"&array[i]);
}
//get the target element from user
printf("Enter number to search");
scanf("%d",&target);
//start searching
for(i=0;i<size;i++) //go through each element of the array
{
if(array[i]==target) //check whether the element at index i matches the target element
{
found=1; //if so then put found to 1 and stop the iteration process
break;
}
}
//if found is equal to one the print number found else not found
if(found==1)
printf("\nNumber found");
else
printf("\nNumber not found");
printf("\npress any key to continue");
getch();
}
Logic: In linear search each element of the array is checked for target element one by one.
Code:
#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,size,target,found;
size=10; //size of the array
int array[size];
//take input from user to fill the array
printf("Welcome\nEnter ten numbers:\n);
for(i=0;i<size;i++)
{
scanf("%d,"&array[i]);
}
//get the target element from user
printf("Enter number to search");
scanf("%d",&target);
//start searching
for(i=0;i<size;i++) //go through each element of the array
{
if(array[i]==target) //check whether the element at index i matches the target element
{
found=1; //if so then put found to 1 and stop the iteration process
break;
}
}
//if found is equal to one the print number found else not found
if(found==1)
printf("\nNumber found");
else
printf("\nNumber not found");
printf("\npress any key to continue");
getch();
}