Tech Point Fundamentals

Wednesday, February 2, 2022

C# Program to Find the Frequency of Array Elements

C# Program to Find the Frequency of Array Elements

coding-interview-question-csharp

Most of the IT companies check the coding skills and problem-solving skills as well along with the theoretical interview questions. Sometimes you are free to write the pseudo code and sometimes you are asked to write the complete program either on any paper or any editor. 


This question is asked in the coding interview to write the program. Here you can find the program as well as a live running program so that you can test the program immediately.


Watch our videos here





Question: 


How can you find the frequency (occurrence) of each element of an array? Write a program to count the frequency of each element of an array?









C# Program to Find the Frequency of Each  Array Element


       
 

// Author 	: Tech Point Fundamentals
// Website 	: www.techpointfunda.com
// Channel	: https://www.youtube.com/c/TechPointFundamentals
// Demo		: Frequency of Each Array Element

using System;
using System.Collections.Generic;

public class Program
{
	public static void Main()
	{
		int[] unsortedArray = new int[8] {1, 2,  6, 4, 3, 4, 2, 4};			
				
		Console.WriteLine("Input UnSorted Array: ");	
		Console.WriteLine("------------------------------------------------ ");	
		for( int i = 0; i < unsortedArray.Length; i++)
		{
			Console.WriteLine(unsortedArray[i]);
		}		
		
		Console.WriteLine("\n\nFrequency of Each Array Element: ");	
		Console.WriteLine("------------------------------------------------ ");	
		FrequencyCount(unsortedArray);					
	}	
	
	public static void FrequencyCount(int[] inputArray)    
	{               
		var frequenyCount = CharCountDictionary(inputArray);             

		foreach (var count in frequenyCount)    
		{    
			Console.WriteLine(" {0} : {1} Times", count.Key, count.Value);    
		}    
	}   
	
	public static SortedDictionary<int, int> CharCountDictionary(int[] inputArray)    
	{    
	 	SortedDictionary<int, int> countDict = new SortedDictionary<int, int>();    

		foreach (int item in inputArray)    
		{    
			if (!(countDict.ContainsKey(item)))    
			{    
				countDict.Add(item, 1);    
			}    
			else    
			{    
				countDict[item]++;    
			}    
		}    
		return countDict;    
	} 
}





Output: 



               Input UnSorted Array: ------------------------------------------------ 1 2 6 4 3 4 2 4 Frequency of Each Array Element: ------------------------------------------------ 1 : 1 Times 2 : 2 Times 3 : 1 Times 4 : 3 Times 6 : 1 Times


Live Demo






No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.