Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 21: Write a Java program to calculate the frequency of the elements in an array.

Frequency.java

import java.util.Scanner;

public class Frequency
{
	public static void main(String[] args)
	{
		int n;
		
		Scanner s = new Scanner(System.in);
		
		System.out.println("Enter the number of elements to be included in the array");
		n=s.nextInt();
	
		//Input Elements in array
		int a[] = new int[n];
		System.out.println("Enter elements of array");

		for(int i=0; i < n; i++)
		{
			System.out.print("Enter "+(i+1)+" element: ");
			a[i]=s.nextInt();	
		}
		
		//Determining the Frequency of the elements in the array.
		int frq[] =new int[n];
		int visited = -1;
	
		for(int j=0;j < a.length;j++)
		{
			int count = 1;
			for(int k=j+1;k < a.length;k++)
			{
				if(a[j]==a[k])
				{
					count++;
					frq[k] = visited;
				}
			}
		
			if(frq[j]!=visited)
			{
				frq[j] = count;
			}
		}
		
		//Displaying the frequency of elements of the array.
		System.out.println();
		System.out.println("Element"+" | "+"Frequency");
		for(int i=0;i < n;i++)
		{
			if(frq[i]!=visited)
			{
				System.out.println("  "+ a[i]+" | "+frq[i]);
			}
		}
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.