hello everyone,
while removing duplicate elements from an array, if more than 4 array elements are same then removal does not work. however my logic seems to be alright. i reckon there is a problem with the conditions and assignments in the three for loops that i have used. the program is as follows:
Code:
/*c program to remove duplicate elements in an array*/
#include<stdio.h>
int main(void)
{
int array[30],i,j,k,n;
printf("\n How many elements:");
scanf("%d",&n);
printf("\n Enter the elements in the array:");
for(i=1;i<=n;i++)
{
scanf("%d",&array[i]);
}
for(i=1;i<=n-1;i++)/*main loop*/
{
for(j=i+1;j<=n;j++)/*secondary loop with which the elements of the main loop will be compared*/
/*since the comparison will be between ith and the (i+1)th element thatswhy j=i+1*/
{
if(array[i]==array[j])/*if any element of the main loop is found to be equal to any element of the secondary loop*/
{
for(k=j;k<=n;k++)/*loop to shift the elements of the array one place leftwards to take the place of the
removed duplicate element*/
{
array[k]=array[k+1];/*the assignment to facilitate the newly arranged array*/
}
i=1;/*once the array has been rearranged main loop rebegins to check duplicacy in
case there are more than 1 duplicate elements or more than 1 instance of the same element*/
n--;/*for each removal of any duplicate element the number of total elements in array decreases by 1*/
}
}
}
printf("\n Array after removing duplicate elements is:");
for(i=1;i<=n;i++)
{
printf("\t %d",array[i]);/*printing the pruned array*/
}
return 0;
}
take for instance if the input elements are 1,1,1,1,1,2,2,3,5 then after removal of duplicacy the array is 1,1,2,3,5. please help!