Write a program that reads an array and deletes duplicate elements in an 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, k;
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 loop over the array
for(i=0; i<N; i++)
{
// for each element, we check
// the remaining elements
for(j=i+1; j<N; j++)
{
// if we find a duplicate
if(A[i] == A[j])
{
// we shift the remaining elements one cell backward
for(k=j; k<N-1; k++)
A[k] = A[k + 1];
// we decrement N after removing the duplicated element
N--;
// If shifting of elements occur then don't increment j
j--;
}
}
}
printf("After deleting duplicates elements : ");
for(i=0; i<N; i++)
printf("%d ", A[i]);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Series values