Skip to main content

Find the frequency of each element in an array in c#

Csharp program for Find the frequency of each element in an array. Here more information.

// Include namespace system
using System;
using System.Collections.Generic;
using System.Collections;
public class Occurrence
{
	// Function which is display array elements
	public static void display(int[] arr)
	{
		for (var i = 0; i < arr.Length; ++i)
		{
			Console.Write("   " + arr[i]);
		}
		Console.Write("\n");
	}
	// Count occurrence of given array
	public static void frequency(int[] arr)
	{
		// Display given array
		Occurrence.display(arr);
		// Create a empty dictionary
		var map = new Dictionary < int , int > ();
		for (var i = 0; i < arr.Length; i++)
		{
			if (map.ContainsKey(arr[i]))
			{
				// When key exists then update value
				map[arr[i]] = map[arr[i]] + 1;
			}
			else
			{
				// Add new element
				map[arr[i]] = 1;
			}
		}
		Console.WriteLine("  Occurrence ");
		//  Display calculated result
		foreach(KeyValuePair < int, int > entry in map)
		{
			Console.WriteLine("  " + entry.Key + "  :  " +  entry.Value);
		}
	}
	public static void Main(String[] args)
	{
		// Array element
		int[] arr = {
			1 , 3 , 2 , 1 , 4 , 2 , 7 , 9 , 1 , 3 , 3 , 4 , 7
		};
		Occurrence.frequency(arr);
	}
}

Output

   1   3   2   1   4   2   7   9   1   3   3   4   7
  Occurrence
  1  :  3
  3  :  3
  2  :  2
  4  :  2
  7  :  2
  9  :  1




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment