C Program to Count Frequency of each Element in an Array

In this tutorial, i am going to show you how to count the frequency of each element in an array with the help of standard method and function in c programs.

All C Programs to Count Frequency of each Element in an Array

  • C Program to Count Frequency of each Element in an Array using Standard Method
  • C Program to Count Frequency of each Element in an Array using Function

C Program to Count Frequency of each Element in an Array using Standard Method

#include <stdio.h>
 
int main()
{
    int a[10000],b[10000],i,j,n,c=0 ;
   
    printf("Enter size of the array : ");
    scanf("%d", &n);
 
    printf("Enter elements in array : ");
    for(i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }
    
  for(i=0; i<n; i++)
    {
        c=1;
        if(a[i]!=-1)
		{
		    for(j=i+1; j<n; j++)
     
            {
        	   if(a[i]==a[j])
        	    {
			       c++;
			       a[j]=-1;
		       }
	       }
	       b[i]=c;
		}
         
   
          
    }
     
        
         
 for(i=0; i<n; i++)
    {
         if(a[i]!=-1)
        {
        	printf("no of %d is %d \n",a[i],b[i]);
 
		} 
         
    }    
    return 0;
} 

The result of the above c program; as follows:

Enter size of the array : 5
Enter elements in array : 5 2 5 6 4
no of 5 is 2 
no of 2 is 1 
no of 6 is 1 
no of 4 is 1 

C Program to Count Frequency of each Element in an Array using Function

#include <stdio.h>
 
count(int *a,int *b,int n)
{ 
    int i,c,j;
    for(i=0; i<n; i++)
    {
        c=1;
        if(a[i]!=-1)
		{
		    for(j=i+1; j<n; j++)
     
            {
        	   if(a[i]==a[j])
        	    {
			       c++;
			       a[j]=-1;
		       }
	       }
	       b[i]=c;
		}
         
   
          
    }
     
 }
 
 print(int *a,int *b,int n)
 { 
    int i;
    for(i=0; i<n; i++)
    {
         
        if(a[i]!=-1)
        {
        	printf("no of %d is %d \n",a[i],b[i]);
 
		} 
         
    }
 	
 }
int main()
{
    int a[10000],b[10000],i,n;
   
    printf("Enter size of the array : ");
    scanf("%d", &n);
 
    printf("Enter elements in array : ");
    for(i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }
    
    count(a,b,n);
    
	print(a,b,n);   
    
	return 0;
}

The result of the above c program; as follows:

Enter size of the array : 5 
Enter elements in array : 1 2 34 44 44
no of 1 is 1 
no of 2 is 1 
no of 34 is 1 
no of 44 is 2 

Be First to Comment

Leave a Reply

Your email address will not be published.