Write a program to delete duplicate elements in a list of elements and display it on the screen.
Example:
Input: n = 10, arr[]={12 ,34, 56, 6, 7, 34, 12, 7, 6, 9} Output: Array after delete of duplicate elements: 12 34 56 6 7 9 Duplicate elements are : 12 34 6 7
Approach
C
#include <stdio.h>int main(){int n;printf("Enter number of elements: ");scanf("%d", &n);int arr[n];printf("Enter array numbers: ");for (int i = 0; i < n; i++)scanf("%d", &arr[i]);int duplicate[n];int l = 0;for (int i = 0; i < n; i++){for (int j = i + 1; j < n;){if (arr[j] == arr[i]){duplicate[l] = arr[i];l++;for (int k = j; k < n-1; k++){arr[k] = arr[k + 1];}n--;}else{j++;}}}printf("Array after delete of duplicate elements: ");for (int i = 0; i < n; i++)printf("%d ", arr[i]);printf("\n");printf("Duplicate elements are : ");for (int i = 0; i < l; i++)printf("%d ", duplicate[i]);return 0;}
Java
import java.util.Scanner;public class DeleteDuplicate {public static void main(String[] args) {System.out.println("Enter number of elements: ");Scanner sc = new Scanner(System.in);int n = sc.nextInt();int arr[] = new int[n];System.out.println("Enter array numbers: ");for (int i = 0; i < n; i++) {arr[i] = sc.nextInt();}int duplicate[] = new int[n];int l = 0;for (int i = 0; i < n; i++) {for (int j = i + 1; j < n;) {if (arr[j] == arr[i]) {duplicate[l] = arr[i];l++;for (int k = j; k < n - 1; k++) {arr[k] = arr[k + 1];}n--;} else {j++;}}}System.out.println("Array after delete of duplicate elements: ");for (int i = 0; i < n; i++) {System.out.printf("%d ", arr[i]);}System.out.println();System.out.println("Duplicate elements are : ");for (int i = 0; i < l; i++) {System.out.printf("%d ", duplicate[i]);}}}
No comments:
Post a Comment