Advertisement
ntodorova

Arrays - 09_MostFrequentNumber

Jan 18th, 2013
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.21 KB | None | 0 0
  1. using System;
  2.  
  3. /*
  4.  * 9. Write a program that finds the most frequent number in an array.
  5.  * Example: {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} -> 4 (5 times)
  6.  */
  7. class MostFrequentNumber
  8. {
  9.     static void Main()
  10.     {
  11.         int n;
  12.         int currentTimes = 0;
  13.         int maxTimes = currentTimes;
  14.         int mostFrequent = int.MinValue;
  15.  
  16.         Console.Write("Number of array elemets: ");
  17.         string strN = Console.ReadLine();
  18.  
  19.         if (!int.TryParse(strN, out n))
  20.         {
  21.             Console.WriteLine("Invalid number!");
  22.         }
  23.         else
  24.         {
  25.             int[] array = new int[n];
  26.  
  27.             // Get all array values
  28.             for (int i = 0; i < n; i++)
  29.             {
  30.                 Console.Write("Please enter array element: ");
  31.                 array[i] = int.Parse(Console.ReadLine());
  32.             }
  33.  
  34.             int totalMostFrequent = array[0];
  35.  
  36.             for (int i = 0; i < array.Length; i++)
  37.             {
  38.                 for (int p = i; p < array.Length; p++)
  39.                 {
  40.                     if (array[i] == array[p])
  41.                     {
  42.                         currentTimes++;
  43.                         mostFrequent = array[p];
  44.                     }
  45.                 }
  46.  
  47.                 if (currentTimes > maxTimes)
  48.                 {
  49.                     maxTimes = currentTimes;
  50.                     totalMostFrequent = mostFrequent;
  51.                 }
  52.  
  53.                 currentTimes = 0;
  54.             }
  55.  
  56.             Console.WriteLine("The most frequent number is {0}. It appears {1} times.", totalMostFrequent, maxTimes);
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement