Q1. 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 simple C program that takes an array of integers, checks for duplicate elements, and prints them out.

#include <stdio.h>

int main() {
    int arr[100], n, i, j;
    int isDuplicate;

    // Read the size of the array
    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);

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

    printf("Duplicate elements in the array are: ");
    int foundDuplicate = 0; // Flag to check if any duplicate has been found

    // Check for duplicate elements
    for(i = 0; i < n; i++) {
        isDuplicate = 0; // Reset duplicate flag for new element
        for(j = 0; j < i; j++) {
            if(arr[i] == arr[j]) {
                isDuplicate = 1; // Mark as a duplicate
                break;
            }
        }
        if(isDuplicate) {
            // Check if we've already printed this duplicate
            if (!foundDuplicate) {
                printf("%d ", arr[i]);
                foundDuplicate = 1; // Set the flag after finding the first duplicate
            }
        }
    }

    if (!foundDuplicate) {
        printf("No duplicates found.");
    }

    printf("\n");
    return 0;
}

Explanation:

  1. Input Handling: The program starts by asking the user for the number of elements in the array and then reads the elements.
  2. Duplicate Checking:
    • We use two nested loops to compare each element with the others before it.
    • If a duplicate is found, it checks if it has been printed before to avoid printing the same duplicate multiple times.
  3. Output: Finally, it prints out the duplicate elements or states that none were found.

How to Compile and Run:

You can copy this code into a C file, say find_duplicates.c, then compile and run it using:

gcc find_duplicates.c -o find_duplicates
./find_duplicates

Make sure you have a C compiler like gcc installed on your system.

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. Write a C Program to print the duplicate elements of an array.In this program, you need to print the duplicate elements present
    1. answers icon 1 answer
  3. Write an algorithm and program in C of;1.inserting elements in an array 2.displayimg elements of an array 3.deleting an element
    1. answers icon 1 answer
  4. 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
more similar questions