Reputation:
I want to write a C function that takes an array and its size as input and returns the element of the array that repeats an odd number of times. In the code below, the output should be 3 as the number 3 repeats an odd number of times, but the output is 1, and I can't find the mistake.
#include <stdio.h>
#define size 15
int array_oddrepretition(int * ptr , int n);
int main()
{ int res;
int arr[]={1,2,3,1,2,3,1,1,1,1,3,3,3};
res=array_oddrepretition(arr, size);
printf("Number is : %d",res);
return 0;
}
int array_oddrepretition(int * ptr , int n)
{
int i,j,count=0,index=0;
for(i=0 ; i<size ; i++)
{
for(j=i+1 ; j<size ; j++)
{
if(ptr[i]==ptr[j])
{
index=i;/* to be able to return the value of this number*/
count++;
}
}
/*so if ptr[j] != ptr [i] we need to check if it odd or not
*if odd break; and return num * if even reset he count and start i=1*/
if(count %2 != 0)
{
break;
}
/* reset the count value before check for the next array element */
count=0;
}
return ptr[index];
}
Upvotes: 0
Views: 51
Reputation: 412
As you put j in the instated loop is j=i+1 which will cause error as you will not check on the index itself , so it will be counted as 3 not 4 as the first count not be counted so the result will be 1 not 3 */ so you should put j=0 and it will works successfully
#include <stdio.h>
#define size 15
int array_oddrepretition(int * ptr , int n);
int main()
{ int res;
int arr[]={1,2,3,1,2,3,1,1,1,1,3,3,3};
res=array_oddrepretition(arr, size);
printf("Number is : %d",res);
return 0;
}
int array_oddrepretition(int * ptr , int n)
{
int i,j,count=0,index=0;
for(i=0 ; i<size ; i++)
{
for(j=0 ; j<size ; j++)
{
if(ptr[i]==ptr[j])
{
index=i;/* to be able to return the value of this number*/
count++;
}
}
/*so if ptr[j] != ptr [i] we need to check if it odd or not
*if odd break; and return num * if even reset he count and start i=1*/
if(count %2 != 0)
{
break;
}
/* reset the count value before check for the next array element */
count=0;
}
return ptr[index];
}
Upvotes: 2