hey guys i have written this function to list the elements in an array without
repetition. i.e if an int array with repeating elements is passed to the function,it should return all the numbers in the array without repeating.
eg:
Code:
input={1, 1, -1, 1, 2, 3, 23, 23, 1, 10, 99, -1}
output={1, -1, 2, 3, 23, 10, 99}
Code:
#include<iostream.h>
#include<stdio.h>
void count(int input1[],int);
int main()
{
int size;
cout<<endl<<"ENTER SIZE OF ARRAY";
cin>>size;
int input[size];
cout<<endl<<"ENTER ELEMENTS OF AN ARRAY TO LIST THE NUMBERS IN IT WITHOUT REPITITION"<<endl;
for(int i=0;i<size;i++)
cin>>input[i];
count(input,size);
}
void count(int input[],int size)
{
int record[size],j; //note:record array keeps a record of the elements encounterd
for(int i=0;i<size;i++)
record[i]=0;
int match=0;
int i,d,index=0;
for(i=0;i<size;i++) //take the elements in input array one by one for comparing with record array
{
//cout<<endl<<"input["<<i<<"]="<<input[i];
match=0; //set flag variable in case the number is already recorded in the record array
for(j=0;j<size;j++)
{
//cout<<endl<<"record["<<j<<"]="<<record[j];
if(input[i]==record[j])
{
//cout<<endl<<record[j];
match=1; //if match set flag vaiable
}
}
if(match==0) // if no record of the element has been made yet copy it into the record
record[index++]=input[i];
//cout<<endl<<"j="<<j;
}
for(i=0;i<index;i++)
cout<<endl<<record[i];
}
the above program was not outputting the correct list of elements until these lines were added to the function count:
Code:
for(int i=0;i<size;i++)
record[i]=0;
to be honest i dont know what i have done here..i added these lines because i felt that the record array might contain some of the elements in the 'input' array along with the garbage it is initialized with.
i have tested the code a fair number of times after the modification and its giving the correct output.
Could somebody tell me if the reason for the earlier error is what i guessed it to be?
or can you spot any flaw in the logic?
i just need to be sure as the function is gonna be integrated with other..
also I would be happy if somebody could suggest a more efficient logic to solve the thing..