Ask Question
10 July, 21:58

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.

+4
Answers (1)
  1. 10 July, 23:19
    0
    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
    {

    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
    {

    count = 1;

    for (int j=i+1; 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
    {

    if (freqArray[i]! = 0)

    {

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

    }

    }

    }

    }
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Question 1 of 2. Count Frequency: [50 marks] Write a function that counts the frequencies of array elements. Your program will take an ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers