Write a program that reads an array and finds and counts the total number of duplicate elements.
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
#define NB_ELEMENT 10
void main()
{
int size;
int A[NB_ELEMENT], NB_occ[NB_ELEMENT];
int counter;
int i, j;
do{
printf("Enter the number of elements: ");
scanf("%d", &size);
}while(size<=0 || size > NB_ELEMENT);
for (i = 0; i < size ; i++) {
printf("Enter Element %d: ", i );
scanf("%d", &A[i]);
}
// for each element loop on the rest of the array
// count the number of appearance of the elements
// and save it in a new array
for (i = 0; i<size; i++)
{
counter = 1;
for (j = i; j<size; j++)
if (A[i] == A[j])
{
NB_occ[i] = counter;
counter++;
}
}
printf("\n\nDuplicated elements: ");
counter = 0;
for (i = 0; i<size; i++)
if (NB_occ[i] == 2)
{
printf("%d ", A[i]);
counter++;
}
printf("\nThe number of duplicate elements in the array is equal to: %d \n", counter);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Simulating a garage