Write a program that reads an array and counts and prints duplicate elements in the array.
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#define SIZE 100
void main()
{
int A[SIZE];
int N;
int i, j;
int count=0;
do {
printf("Enter N: ");
scanf("%d", &N);
} while (N <= 0 || N > SIZE);
printf("Enter A: ");
for (i = 0;i < N;i++)
scanf("%d", &A[i]);
// we will loop on the array
// and check if the current element repeats
// in the remaining array
// if it's the case, we will print it
// if it's not repeating, we skip it
// we check all the elements
for (i = 0;i < N;i++)
// for each element, we check the remaining elements
for(j=i+1; j < N; j++)
// if 2 elements are equal, we increment count
// and print the element
if(A[i]==A[j])
{
printf("%d ", A[i]);
count++;
}
printf("Number of duplicate elements is equal to %d\n", count);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Add into a table based on hash coalesced with separated zones