Let X be an array containing n positive integers. Write a program that creates:

  • An array Dist containing the distinct elements of X
  • An array Effec containing the number of occurrence of each distinct element of X
  • An integer k containing the number of distinct elements of X.

 

Example:

  • X={4, 5, 5, 7, 4, 2, 3, 2}
  • Dist={4, 5, 7, 2, 3}
  • Effec={2, 2, 1, 2, 1}
  • K=5

Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#define SIZE 100
void main()
{
	int X[SIZE], Dist[SIZE], Effec[SIZE];
	int k=0,i,j,n;

	do{
		printf("Enter the dimension: ");
		scanf("%d", &n);
	}while(n<=0 || n>SIZE);

	for(i=0;i<n;i++)
	{
		printf("Enter X[%d]=",i);
		scanf("%d", &X[i]);
	}

	for(i=0;i<n;i++)
		for(j=0;j<=k;j++)
		{
			if(k==0 || j>=k)
			{
				Dist[k]=X[i];
				Effec[k]=1;
				k++;
				break;
			}
			if (X[i]==Dist[j])
			{
				Effec[j]++;
				break;
			}

		
		}

	printf("\nX    :{");
	for(i=0;i<n;i++)
		printf("%d, ",X[i]);
	printf("\b\b}");

	printf("\nDist :{");
	for(i=0;i<k;i++)
		printf("%d, ",Dist[i]);
	printf("\b\b}");

	printf("\nEffec:{");
	for(i=0;i<k;i++)
		printf("%d, ",Effec[i]);
	printf("\b\b}");
	printf("\n\nk=%d\n\n", k);
}


Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Delete duplicate elements in an array