Find the first repeated element in an array
C program to find the first repeated element in an 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 first_rep(int a[MAX], int n)
{
int i, j, num, flag = 0;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i] == a[j])
{
num = a[i];
flag = 1;
break;
}
}
if(flag == 1)
break;
}
if(flag == 0)
printf("\nThere is no repeating element");
else
printf("\nFirst repeated element is %d",num);
}
void main()
{
int arr[MAX];
int i, n;
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);
first_rep(arr, n);
getch();
}
Output
********** Run1 **********
Enter the number of elements in the array :5
Enter the elements of the array
Element 1 :1
Element 2 :2
Element 3 :3
Element 4 :4
Element 5 :5
There is no repeating element
********** Run2 **********
Enter the number of elements in the array :5
Enter the elements of the array
Element 1 :1
Element 2 :2
Element 3 :3
Element 4 :2
Element 5 :1
First repeated element is 1