Ads Top

Find the most frequent element in an Array


1:  class Program  
2:   {  
3:   static void Main(string[] args)  
4:   {  
5:   int j, maxCount, maxElement = 0, count = 0;  
6:   maxCount = 0;  
7:   //Take input numbers from user  
8:   Console.WriteLine("\n Enter 10 Numbers : ");  
9:   int[] numbers = new int[10];  
10:   string arr1 = "";  
11:   for (int i = 0; i < 10; i++)  
12:   {  
13:   arr1 = Console.ReadLine();  
14:   numbers[i] = Convert.ToInt32(arr1);  
15:   }  
16:   /* Count the frequency of every elemenet of array,   
17:   and check if it is greater than maximum count element   
18:   we found till now and update it accordingly */  
19:   for (int i = 0; i < numbers.Length; i++)  
20:   {  
21:   count = 1;  
22:   for (j = i + 1; j < numbers.Length; j++)  
23:   {  
24:   if (numbers[j] == numbers[i])  
25:   {  
26:   count++;  
27:   /* If count of current element is more than   
28:   maxCount, uodate maxCount and maxElement */  
29:   if (count > maxCount)  
30:   {  
31:   maxCount = count;  
32:   maxElement = numbers[j];  
33:   }  
34:   }  
35:   }  
36:   }  
37:   Console.WriteLine("Most Frequent Element in an Array : {0} \n Count : {1} Times", maxElement, maxCount);  
38:   Console.ReadLine();  
39:   }  
40:   }  
Powered by Blogger.