Answer to Question #197767 in C for Prasanna

Question #197767

From a set of array elements, find the number of occurrences of each element present in the given array.


1
Expert's answer
2021-05-25T17:55:56-0400
#include <stdio.h>    
     
int main()    
{    
    //Initialize an array of ints
    int myArray[] = {4, 5, 6, 7, 2, 6, 8, 4, 7};     
        
    //Get array size
    int length = sizeof(myArray) / sizeof(myArray[0]);    
    int frequency[length]; //Array to store frequency of element    
    int visited = -1;    
        
    for(int i = 0; i < length; i++)
    {    
        int count = 1;    
        for(int j = i+1; j < length; j++)
        {    
            if(myArray[i] == myArray[j])
            {    
                count++;    
                frequency[j] = visited;  //Ensures element is only counted once 
            }    
        }    
        if(frequency[i] != visited)    
        {
            frequency[i] = count;  
        }
    }    
        
    //Displays the frequency of each element 
    printf("Element  Frequency\n");
    for(int i = 0; i < length; i++)
    {    
        if(frequency[i] != visited)
        {    
            printf("%d \t : %d \n", myArray[i], frequency[i]);   
        }    
    }
    return 0;    
}  

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS