ellapt

T7.9.MostFrequentNumber

Jan 15th, 2013
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. using System;
  2.  
  3. class MostFrequentNumber
  4. {
  5. static void Main()
  6. {
  7. string inputVar;
  8. uint n;
  9. Console.WriteLine("Find the most frequent number in an array");
  10. do
  11. {
  12. Console.Write("Enter array length: ");
  13. }
  14. while (!(uint.TryParse(inputVar = Console.ReadLine(), out n)) || n == 0);
  15.  
  16. int[] arrayOfints = new int[n];
  17.  
  18. Console.WriteLine("Enter the elements of the array (please, enter at least one positive number):");
  19. for (int i = 0; i < n; i++)
  20. {
  21. arrayOfints[i] = int.Parse(Console.ReadLine());
  22. }
  23. Array.Sort(arrayOfints);
  24. for (int i = 0; i < n; i++)
  25. {
  26. Console.WriteLine("{0},",arrayOfints[i]);
  27. }
  28. Array.Sort(arrayOfints);
  29. int cnt = 1;
  30. int maxCnt = 0;
  31. int mostFrq = arrayOfints[0];
  32. int finalValue = mostFrq;
  33.  
  34. for (int i = 1; i < n; i++)
  35. {
  36. if (arrayOfints[i] == mostFrq)
  37. {
  38. cnt += 1;
  39. }
  40. else
  41. {
  42. mostFrq = arrayOfints[i];
  43. cnt=1;
  44. }
  45. if (maxCnt < cnt)
  46. {
  47. maxCnt = cnt;
  48. finalValue = arrayOfints[i - 1];
  49. }
  50. }
  51. Console.WriteLine("The most frequent number is {0}; it occurs {1} times.",finalValue,maxCnt);
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment