C Program To Search An Element In An Array

In this tutorial, i am going to show you how to search an element in an array with the help of standard method, function and recursion in c programs.

All C Programs To Search An Element In An Array

  • C Program To Search An Element In An Array using Standard Method
  • C Program To Search An Element In An Array using Function
  • C Program To Search An Element In An Array using Recursion

C Program To Search An Element In An Array using Standard Method

#include <stdio.h>
int main()
{
    int a[10000],i,n,key;
   
    printf("Enter size of the  array : ");
    scanf("%d", &n);
    printf("Enter elements in array : ");
    for(i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }
     printf("Enter the key : ");
    scanf("%d", &key);
     
    for(i=0; i<n; i++)
    {
        if(a[i]==key)
        {
			printf("element found ");
            return 0;		 
        }
 
    }
    
	printf("element  not  found");
}

The result of the above c program; as follows:

Enter size of the  array : 5
Enter elements in array : 1 5 4 8 9
Enter the key : 4
element found 

C Program To Search An Element In An Array using Function

#include <stdio.h>
 
int search(int *a,int n,int key)
{ 
int i;
    for(i=0; i<n; i++)
    {
        if(a[i]==key)
        {
             return 1;		 
        }
 
    }
    
return 0;          
      
 }
 
 
  
int main()
{
    int a[10000],i,n,key;
   
    printf("Enter size of the  array : ");
    scanf("%d", &n);
    printf("Enter elements in array : ");
    for(i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }
     printf("Enter the key : ");
    scanf("%d", &key);
    
     if(search(a,n,key))
     printf("element found ");
     else
     printf("element not found ");
     
    
}

The result of the above c program; as follows:

Enter size of the  array : 5
Enter elements in array : 4 7 6 9 8
Enter the key : 4
element found 

C Program To Search An Element In An Array using Recursion

#include <stdio.h>
 
int search(int *a,int i,int n,int key)
{ 
    if(i<n)
    {
    	if(a[i]==key)
    	return 1;
    	
    	return search(a,i+1,n,key);
    	
	}
    
return 0;          
      
 }
 
 
  
int main()
{
    int a[10000],i,n,key;
   
    printf("Enter size of the  array : ");
    scanf("%d", &n);
    printf("Enter elements in array : ");
    for(i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }
     printf("Enter the key : ");
    scanf("%d", &key);
    
     if(search(a,0,n,key))
     printf("element found ");
     else
     printf("element not found ");
     
    
}

The result of the above c program; as follows:

Enter size of the  array : 5
Enter elements in array : 8 7 9 4 5
Enter the key : 7
element found 

More C Programming Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.