linear search

hey so this is my code for linear search. is there a problem with this?. coz its not comparing and returning if i enter an element which does not exist in the array

#include<stdio.h>
#include<conio.h>
int main()
{
     int A[10]={2,3,4,5,6,7,8,9,1,20};
     int n,item,counter=1,i;
     printf("\nEnter the size of the array");
     scanf("%d",&n);
     printf("\nThe array size is A[%d]",n);
     printf("\nEnter the number you would like to search in the array");
     scanf("%d",&item);
     A[n+1]=item;
     for(i=0;i<n;i++)
     {
        if(A[counter]==item)
        {
          printf("\nItem found in the array!!");
        
        }
        counter++;
     }
       while(A[counter]!=item)            
         {       
                 printf("\nItem not found in the list");
            counter++;
         };
     
getch();
return 0;
 
  
}

Here is my simplest code for linear search:

void main (void)
{
clrscr();
int arr[10],num,count=0;
for(int i=0; i<10;i++)
{
cin>>arr[i];
}
cout<<"enter the number you want to search :"<<endl;
cin>>num;
for (int j=0; j<10; j++)
{
if(arr[j] ==num)   {
count++;
}
}
if(count>0)
{
cout<<num<<" found! , and its occurence is :" <<count<<" times";
}
else if(count==0){
cout<<num<<" not found!";
}
getch();
}

Hello,

You can do a linear search in a much easier fashion…

You can encapsulate it inside a function and do it with a simple for loop, like this:

int lin_search(int arr[],int size, int element_to_search)
{
      for(int i = 0; i < size; i++)
      {
          if(arr[i] == element_to_search)
              return 1;
      }
      return 0;
}

The above C-style function to perform a linear search, receives as input, the array, its size and an element to search for.

Note that as you return 1 as soon as you found the element, you can safely assume that when the function returns 0, the element is not present in the array.

The program I wrote below uses this function:

#include <stdio.h>

int lin_search(int arr[], int size, int elem_to_search)
{
	int i;
	for(i=0; i < size; i++)
	{
		if(arr[i] == elem_to_search)
			return 1;
	}
	return 0;
}

int main()
{
	int arr[7] = {2,3,4,5,-3,12,9};
	int elem_to_look_for;
	scanf("%d",&elem_to_look_for);
	if(lin_search(arr,7,elem_to_look_for)==1)
		puts("Element found.");
	else
		puts("Element not in array.");
	return 0;
}

Hope it helps you out!

Best regards,

Bruno

1 Like
//