cortez

Most frequent number in Array

Jul 2nd, 2013
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.86 KB | None | 0 0
  1. //Find the most frequent number in the array:
  2.  
  3. Console.WriteLine("Enter length of the array: ");
  4. int length;
  5.  
  6. //Length must be non-negative integer.
  7. do
  8. {
  9.     Console.Write("Length = ");
  10. }
  11. while(!int.TryParse(Console.ReadLine(), out length) || length < 0);
  12.  
  13. int[] array = new int[length];
  14.  
  15. for(int i = 0; i < length; i++)
  16. {
  17.     array[i] = Console.ReadLine();
  18. }
  19.  
  20. int mostFrequent = 0;
  21. int maxCount = 0;
  22.  
  23. for(int i = 0; i < array.Length; i++)
  24. {
  25.   int counter = 0;// declaring the temp counter which will count the current occurrences of the number.
  26.  
  27.   for(int j = 0; j < array.Length; j++)
  28.   {
  29.       if(array[j] == array[i])
  30.       {
  31.           counter++;
  32.       }
  33.   }
  34.   if(counter > maxCount)
  35.   {
  36.       maxCount = counter;
  37.       mostFrequent = array[i];
  38.   }
  39. }
  40. Console.WriteLine("Most frequent number in array: {0}\nRepeated {1}", mostFrequent, maxCount);
Advertisement
Add Comment
Please, Sign In to add comment