Program to find the first repeating element in an array of integers in C++
Written by
C++ program to find the first repeating element in an array of integers
Example:
Input: {5, 15, 20, 5, 6, 10, 15, 10}
Output: 5
# Algorithm
- Take an array as input and store its size in a variable
n
. - Start a loop from
i
= 0 toi
<n
, which will select each element from the array. - Inside the loop, start a second loop from
j
=i
+ 1 toj
<n
to traverse ahead and check for duplicates. - If a duplicate is found (i.e.,
array[i]
is equal toarray[j]
), print the first repeating integer and return 0. - Else, print "No integer repeated".
Code:
#include <bits/stdc++.h>
using namespace std;
int main() {
int array[100], n, i;
cout << "Enter number of elements: ";
cin >> n;
cout << "\nEnter elements: ";
for (i = 0; i < n; i++)
cin >> array[i];
cout << "Original array: ";
for (int i = 0; i < n; i++)
cout << array[i] << " ";
// selecting an element
for (int i = 0; i < n; i++)
// traversing to check repetition
for (int j = i + 1; j < n; j++)
if (array[i] == array[j]) {
cout << "\nFirst repeating integer is " << array[i];
return 0;
}
cout << "No integer repeated\n";
return 0;
}
Output
Enter number of elements: 5
Enter elements: 1 2 3 4 5
Original array: 1 2 3 4 5
No integer repeated
Time Complexity: O(N2)