Javatpoint Logo
Javatpoint Logo

Q. Program to find the frequency of each element of an array.

Explanation

In this program, we need to count the occurrence of each unique element present in the array. One of the approach to resolve this problem is to maintain one array to store the counts of each element of the array. Loop through the array and count the occurrence of each element and store it in another array fr.

Program to find the frequency of each element of an array

In the above array, 1 has appeared 1 time, so, the frequency of 1 is 1. Similarly, 2 has appeared 4 times. The frequency of 2 is 4 and so on.

Algorithm

  1. Declare and initialize an array arr.
  2. Declare another array fr with the same size of array arr. It is used to store the frequencies of elements present in the array.
  3. Variable visited will be initialized with the value -1. It is required to mark an element visited that is, it helps us to avoid counting the same element again.
  4. The frequency of an element can be counted using two loops. One loop will be used to select an element from an array, and another loop will be used to compare the selected element with the rest of the array.
  5. Initialize count to 1 in the first loop to maintain a count of each element. Increment its value by 1 if a duplicate element is found in the second loop. Since we have counted this element and didn't want to count it again. Mark this element as visited by setting fr[j] = visited. Store count of each element to fr.
  6. Finally, print out the element along with its frequency.

Solution

Python

Output:

----------------------------
Element | Frequency
----------------------------
         1    |    2
         2    |    4
         8    |    1
         3    |    1
         5    |    1
----------------------------

C

Output:

----------------------------
Element | Frequency
----------------------------
         1    |    2
         2    |    4
         8    |    1
         3    |    1
         5    |    1
----------------------------

JAVA

Output:

----------------------------
Element | Frequency
----------------------------
         1    |    2
         2    |    4
         8    |    1
         3    |    1
         5    |    1
----------------------------

C#

Output:

----------------------------
Element | Frequency
----------------------------
         1    |    2
         2    |    4
         8    |    1
         3    |    1
         5    |    1
----------------------------

PHP

Output:

----------------------------
Element | Frequency
----------------------------
         1    |    2
         2    |    4
         8    |    1
         3    |    1
         5    |    1
----------------------------

Next Topic#




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA