Write a C Program to print the duplicate elements of an array.

In this program, you need to print the duplicate elements present in the array.

1 answer

Certainly! Below is a C program that identifies and prints the duplicate elements in an array. The program uses a simple nested loop approach to check for duplicates.

#include <stdio.h>

int main() {
    int n, i, j;
    
    // Read the size of the array
    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);
    
    int arr[n]; // Declare the array

    // Read the elements of the array
    printf("Enter the elements of the array:\n");
    for (i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    printf("Duplicate elements in the array are:\n");
    
    // Check for duplicates
    for (i = 0; i < n; i++) {
        int isDuplicate = 0; // Flag to check if the element is already printed
        for (j = 0; j < i; j++) {
            if (arr[i] == arr[j]) {
                isDuplicate = 1; // It is a duplicate
                break;
            }
        }
        
        if (!isDuplicate) { // If not already marked as duplicate
            for (j = i + 1; j < n; j++) {
                if (arr[i] == arr[j]) {
                    printf("%d ", arr[i]);
                    break;
                }
            }
        }
    }
    
    return 0;
}

Explanation:

  1. Input the Size of the Array: We first ask the user for the number of elements in the array.
  2. Input the Array Elements: We then read the elements of the array from the user.
  3. Finding Duplicates:
    • We use two loops. The outer loop iterates through each element of the array.
    • The inner loop (first) checks if the current element has already been printed as duplicate by comparing it with previous elements.
    • The inner loop (second) checks how many times the current element appears later in the array.
  4. Output the Duplicates: If a duplicate is found, it prints it.

Note:

This program may not handle the case of larger arrays well since C does not manage memory automatically. For larger datasets or more efficient duplicate handling, consider using hash tables or sorting algorithms along with a linear scan.

Similar Questions
  1. Write a C Program to print the duplicate elements of an array.EXPLANATION In this program, you need to print the duplicate
    1. answers icon 1 answer
  2. Q1. Write a C Program to print the duplicate elements of an array.In this program, you need to print the duplicate elements
    1. answers icon 1 answer
  3. 1. Elements – sequence-series outputtingWrite a program that prints the following elements: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19,
    1. answers icon 0 answers
  4. Elements – sequence-series outputtingWrite a program that prints the following elements: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19,
    1. answers icon 2 answers
more similar questions