Advertisement
svetoslavhl

Untitled

May 21st, 2014
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. //9. Write a program that finds the most frequent number in an array.
  2. //Example: {4 1, 1,4 2, 3,4 4, 1, 2, 4, 9, 3} -> 4 (5 times)
  3.  
  4.  
  5. using System;
  6.  
  7. class Program
  8. {
  9. static void Main(string[] args)
  10. {
  11. //int[] array = { 2, 2, 1, 4, 2, 3, 2, 4, 1, 2, 4, 2, 2 };
  12. Console.WriteLine("Enter the array's lenght:");
  13. int size = int.Parse(Console.ReadLine());
  14.  
  15. int[] array = new int[size];
  16.  
  17. //Entering the values of the array from the console
  18.  
  19. for (int i = 0; i < array.Length; i++)
  20. {
  21.  
  22. Console.Write("array[{0}] = ", i);
  23. array[i] = int.Parse(Console.ReadLine());
  24.  
  25.  
  26. }
  27.  
  28.  
  29.  
  30. //Calculating the most frequent number in the sequence
  31.  
  32. int frequency = 0;
  33. int maxFrequency = 0;
  34. int mostFreqNum = 0;
  35. for (int i = 0; i < array.Length; i++)
  36. {
  37.  
  38.  
  39. frequency = 1;
  40. for (int j = i + 1; j < array.Length; j++)
  41. {
  42.  
  43. if (array[i] == array[j])
  44. {
  45.  
  46. frequency++;
  47.  
  48. }
  49. }
  50.  
  51. if (frequency > maxFrequency)
  52. {
  53. maxFrequency = frequency;
  54. mostFreqNum = array[i];
  55. }
  56. }
  57.  
  58.  
  59. //Printing the result
  60.  
  61. for (int i = 0; i < array.Length; i++)
  62. {
  63. if (i == 0)
  64. {
  65. Console.Write("{");
  66. }
  67.  
  68. Console.Write("{0}, ", array[i]);
  69.  
  70.  
  71.  
  72. if (i == array.Length - 1)
  73. {
  74.  
  75. Console.Write("}");
  76.  
  77. }
  78.  
  79.  
  80.  
  81. }
  82.  
  83. Console.Write(" ----> ");
  84.  
  85. Console.Write("{0} ({1} times)", mostFreqNum, maxFrequency);
  86.  
  87. Console.WriteLine();
  88.  
  89.  
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement