Question 1 of 2. Count Frequency: [50 marks] Write a function that counts the frequencies of array elements. Your program will take an array as input from the user. Write a function called CountFreq(...) that takes the array as a parameter and print all elements and their frequencies. You can print the elements in any order.

Answer :

ijeggs

Answer:

The solution (Java programming Language) is given in the explanation section

Pay attention to comments for explanation

Explanation:

import java.util.Scanner;

public class num2 {

   public static void main(String[] args) {

       //Calling the CountFreq in the main method

       CountFreq();

   }

   //Defining the CountFreq Method

   public static void CountFreq(){

       Scanner in = new Scanner(System.in);

       System.out.println("Enter array size");

       int arrSize = in.nextInt();

       //Creating the array

       int [] arr = new int[arrSize];

       //Creating another array to hold number frequencies

       int [] freqArray = new int[arr.length];

       //For counting occurence of a the same number

       int count;

       //Receiving the elements of the array

       System.out.println("Enter array Elements: ");

       for(int i=0; i<arr.length; i++)

       {

           System.out.println("Enter the values");

           arr[i] = in.nextInt();

           System.out.printf("%d",arr[i]);

           //Intialize frequency to -1

           freqArray[i] = -1;

       }

       //Checking for occurence of numbers, Increasing the count variable

       //Avoiding duplicates

       for(int i=0; i<arr.length; i++)

       {

           count = 1;

           for(int j=i+1; j<arr.length; j++)

           {

               //Check for duplicate

               if(arr[i]==arr[j])

               {

                   count++;

                   // Avoid counting same element twice

                   freqArray[j] = 0;

               }

           }

           //If frequency of current element is not counted

           if(freqArray[i] != 0)

           {

               freqArray[i] = count;

           }

       }

       //Output of frequencies

       System.out.println("Frequency of all elements of array");

       for(int i=0; i<arr.length; i++)

       {

           if(freqArray[i] != 0)

           {

               System.out.printf("%d occurs %d times\n", arr[i], freqArray[i]);

           }

       }

   }

   }

Other Questions