Shamsh Sameed Ahsan Shamsh Sameed Ahsan - 1 year ago 100
C Question

Count number of repeating elements in an array in C

This program is for counting number of occurrences of each unique element.
Output is:

Program:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int *input;
int n,c;

printf("Enter the number of elements in the array:");
scanf("%d",&n);

input = (int *) malloc(n*sizeof(int));

printf("Enter %d elements \n",n);
for(c=0; c<n; c++)
scanf("%d",input+c);//POINTER NOTATION

if (sizeof(input) == 0) return 0;

int prev = input[0];
int count = 1;
int i;
int ARRAYSIZE = sizeof(input) / sizeof(int);

for (i = 1; i < ARRAYSIZE; i++)
{

if (input[i] == prev)
{
count++;
}
else
{
printf("%d=%d ", prev, count);
prev = input[i];
count = 1;
}

}

printf("%d=%d\n", prev, count);
free(input);
return 0;
}


Enter the number of elements in the array:10

Enter 10 elements

1 1 1 1 1 2 2 3 3 6

1=1

Here I have entered 1 (5 times), 2 (2 times), 3 (2 times) and 6 (once)
But as you can see it only gives 1=1(1 times, but I've entered 1 five times.)
Can someone please help me out? Thanks.

Answer Source

You do not need this:

int ARRAYSIZE = sizeof(input) / sizeof(int);

Use n in place of ARRAYSIZE.

sizeof(input) returns the size of the pointer, input, not the size of the array. The for loop is not executed, the output is from the outer printf.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download