In this tutorial, you will learn how to write Java program to print the first duplicate number of an array.
This program is going to be very simple. Below are the approach which we will be follow to achieve our solution:
- In this program, we need to check if one of the first numbers is duplicated, then print that number and exit the program.
- To check this, we compare an array element with the next element. If it matches, it will be printed.
- We will use the concept of the for loop and the if-else statement to achieve the desired output.
How will our program behave?
As we have already seen above, our logic is to find the first duplicate number in Java.
Our program takes an array as input.
And based on the input, it will compare each element with the next one. If a match is found, it will print that number as a duplicate number, otherwise it will go to the next index and perform the same operation.
Program to find first duplicate number in Java
import java.util.*;
public class ArrayExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of array: ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter " + n + " array elements between 0 to " + (n - 1));
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < n - 1; i++) {
if (arr[i] == arr[i + 1]) {
System.out.println(arr[i] + " is first duplicate number");
break;
}
if (i == (n - 2)) {
System.out.println("No duplicate number");
}
}
}
}
Output
Enter the size of array:
5
Enter 5 array elements between 0 to 4
1
2
3
3
4
3 is first duplicate number