C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Q. Program to print the duplicate elements of an array.ExplanationIn this program, we need to print the duplicate elements present in the array. This can be done through two loops. The first loop will select an element and the second loop will iteration through the array by comparing the selected element with other elements. If a match is found, print the duplicate element. In the above array, the first duplicate will be found at the index 4 which is the duplicate of the element (2) present at index 1. So, duplicate elements in the above array are 2, 3 and 8. Algorithm
SolutionPython#Initialize array arr = [1, 2, 3, 4, 2, 7, 8, 8, 3]; print("Duplicate elements in given array: "); #Searches for duplicate element for i in range(0, len(arr)): for j in range(i+1, len(arr)): if(arr[i] == arr[j]): print(arr[j]); Output: Duplicate elements in given array: 2 3 8 C#include <stdio.h> int main() { //Initialize array int arr[] = {1, 2, 3, 4, 2, 7, 8, 8, 3}; //Calculate length of array arr int length = sizeof(arr)/sizeof(arr[0]); printf("Duplicate elements in given array: \n"); //Searches for duplicate element for(int i = 0; i < length; i++) { for(int j = i + 1; j < length; j++) { if(arr[i] == arr[j]) printf("%d\n", arr[j]); } } return 0; } Output: Duplicate elements in given array: 2 3 8 JAVApublic class DuplicateElement { public static void main(String[] args) { //Initialize array int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3}; System.out.println("Duplicate elements in given array: "); //Searches for duplicate element for(int i = 0; i < arr.length; i++) { for(int j = i + 1; j < arr.length; j++) { if(arr[i] == arr[j]) System.out.println(arr[j]); } } } } Output: Duplicate elements in given array: 2 3 8 C#using System; public class DuplicateElement { public static void Main() { //Initialize array int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3}; Console.WriteLine("Duplicate elements in given array: "); //Searches for duplicate element for(int i = 0; i < arr.Length; i++) { for(int j = i + 1; j < arr.Length; j++) { if(arr[i] == arr[j]) Console.WriteLine(arr[j]); } } } } Output: Duplicate elements in given array: 2 3 8 PHP<!DOCTYPE html> <html> <body> <?php //Initialize array $arr = array(1, 2, 3, 4, 2, 7, 8, 8, 3); print("Duplicate elements in given array: <br>"); //Searches for duplicate element for($i = 0; $i < count($arr); $i++) { for($j = $i + 1; $j < count($arr); $j++) { if($arr[$i] == $arr[$j]) print($arr[$j] . "<br>"); } } ?> </body> </html> Output: Duplicate elements in given array: 2 3 8
Next Topic#
|