Write a C Program for Linear search in an array

#include #define MAX 50 int LinearSearch(int arr[],int n,int item); int main(void) { int i,n,item,arr[MAX],index; printf("Enter the number
Admin

C Program for Linear search in an array

This Program will Takes 3 inputs

  1. For the size of array
  2. Input for arrays
  3. Element to be searched in array
If element is available it will return index else -1.
#include <stdio.h>
#define MAX 50
int LinearSearch(int arr[],int n,int item);
int main(void)
{
	int i,n,item,arr[MAX],index;
	printf("Enter the number of elements : ");
	scanf("%d",&n);
	printf("Enter the elements : \n");
	for(i=0; i<n; i++)
		scanf("%d", &arr[i]);
	printf("Enter the item to be searched : ");
	scanf("%d", &item);
	index=LinearSearch(arr,n,item);
	if(index==-1)
		printf("%d not found in array\n",item);
	else
		printf("%d found at position %d\n",item,index);
	return 0;
}

int LinearSearch(int arr[],int n,int item)
{
	int i=0;
	while(i<n && item!=arr[i])
		i++;
	if(i<n) 
		return i;
	else
		return -1;
}
Output
Enter the number of elements : 7
Enter the elements : 
12 13 14 15 16 17 18
Enter the item to be searched : 13
13 found at position 1

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.