Topic-36:Duplicate element of an Array

Detecting duplicate elements in an array involves checking whether there are any elements that appear more than once within the array.

Example:

#include <stdio.h>

 

#define MAX_SIZE 100

 

// Function to check for duplicate elements in an array

void findDuplicates(int array[], int size) {

    // Iterate through the array

    for (int i = 0; i < size – 1; i++) {

        for (int j = i + 1; j < size; j++) {

            // If duplicate found

            if (array[i] == array[j]) {

                printf(“Duplicate element found: %d\n”, array[i]);

            }

        }

    }

}

 

int main() {

    int arr[MAX_SIZE] = {2, 4, 6, 2, 7, 4, 8, 1, 9, 5}; // Example array

    int size = 10; // Current size of the array

 

    // Call the findDuplicates function to check for duplicates

    findDuplicates(arr, size);

 

    return 0;

}

 

    Explanation:

    • We have a function findDuplicates that takes the array and its size as parameters.
    • Inside findDuplicates, we use nested loops to iterate through the array.
    • For each element at index i, we compare it with every element at indices greater than i (starting from i + 1).
    • If we find any two elements that are equal, we print a message indicating the presence of a duplicate element.
    • In the main function, we define an example array arr and its size size.
    • We call the findDuplicates function to check for duplicate elements in the array arr.
    • If duplicates are found, their values are printed. Otherwise, no output is produced, indicating no duplicates were found.

    Leave a Comment

    Your email address will not be published. Required fields are marked *