Program :-
#include<stdio.h>
int A[100];
int linrsrch(int n,int item) //Function to perform Linear search
{
int i=0;
while(i<n && A[i]!=item) //Searching starts
i+=1;
if(i==n) //Returning values
return -1;
else
return i;
}
void main()
{
int n,i,item,pos;
printf("Enter the array size"); //Reading the array size
scanf("%d",&n);
printf("Enter the array elements"); //Reading the array elements
for(i=0;i<n;++i)
scanf("%d",&A[i]);
printf("Enter the item to be searched"); //Reading the item to be searched
scanf("%d",&item);
pos=linrsrch(n,item); //Finding position of the item
if(pos==-1) //Printing not found if found else position
printf("Item not found");
else
printf("The item %d is found at the position %d",item,pos+1);
}
Output :-
Eg 1:-Enter the array size : 5
Enter the array elements : 32 45 18 25 56
Enter the item to be searched : 23
Item not found
Eg 2:-
Enter the array size : 5
Enter the array elements : 32 45 18 25 56
Enter the item to be searched : 18
The item 18 is found at the position 3
#include<stdio.h>
int A[100];
int linrsrch(int n,int item) //Function to perform Linear search
{
int i=0;
while(i<n && A[i]!=item) //Searching starts
i+=1;
if(i==n) //Returning values
return -1;
else
return i;
}
void main()
{
int n,i,item,pos;
printf("Enter the array size"); //Reading the array size
scanf("%d",&n);
printf("Enter the array elements"); //Reading the array elements
for(i=0;i<n;++i)
scanf("%d",&A[i]);
printf("Enter the item to be searched"); //Reading the item to be searched
scanf("%d",&item);
pos=linrsrch(n,item); //Finding position of the item
if(pos==-1) //Printing not found if found else position
printf("Item not found");
else
printf("The item %d is found at the position %d",item,pos+1);
}
Output :-
Eg 1:-Enter the array size : 5
Enter the array elements : 32 45 18 25 56
Enter the item to be searched : 23
Item not found
Eg 2:-
Enter the array size : 5
Enter the array elements : 32 45 18 25 56
Enter the item to be searched : 18
The item 18 is found at the position 3
No comments:
Post a Comment