Search an element in the array
C program to search an element in the array.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void read_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:",i+1);
scanf("%d",&a[i]);
}
}
void main()
{
int arr[MAX];
int i, n, num, flag;
printf("Enter the number of elements in the array\t:");
scanf("%d",&n);
printf("Enter the elements of the array\n");
read_array(arr, n);
printf("Enter the element to be searched\t:");
scanf("%d", &num);
flag = 0;
for(i=0;i<n;i++)
{
if(arr[i]==num)
{
flag = 1;
printf("\nElement found at position %d",i+1);
}
}
if(flag == 0)
printf("\nElement not found");
getch();
}
Output
********** Run1 **********
Enter the number of elements in the array :8
Enter the elements of the array
Element 1 :12
Element 2 :23
Element 3 :25
Element 4 :56
Element 5 :12
Element 6 :45
Element 7 :12
Element 8 :36
Enter the element to be searched :12
Element found at position 1
Element found at position 5
Element found at position 7
********** Run2 **********
Enter the number of elements in the array :8
Enter the elements of the array
Element 1 :12
Element 2 :23
Element 3 :45
Element 4 :56
Element 5 :78
Element 6 :89
Element 7 :85
Element 8 :52
Enter the element to be searched :55
Element not found