Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- /*
- * 9. Write a program that finds the most frequent number in an array.
- * Example: {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} -> 4 (5 times)
- */
- class MostFrequentNumber
- {
- static void Main()
- {
- int n;
- int currentTimes = 0;
- int maxTimes = currentTimes;
- int mostFrequent = int.MinValue;
- Console.Write("Number of array elemets: ");
- string strN = Console.ReadLine();
- if (!int.TryParse(strN, out n))
- {
- Console.WriteLine("Invalid number!");
- }
- else
- {
- int[] array = new int[n];
- // Get all array values
- for (int i = 0; i < n; i++)
- {
- Console.Write("Please enter array element: ");
- array[i] = int.Parse(Console.ReadLine());
- }
- int totalMostFrequent = array[0];
- for (int i = 0; i < array.Length; i++)
- {
- for (int p = i; p < array.Length; p++)
- {
- if (array[i] == array[p])
- {
- currentTimes++;
- mostFrequent = array[p];
- }
- }
- if (currentTimes > maxTimes)
- {
- maxTimes = currentTimes;
- totalMostFrequent = mostFrequent;
- }
- currentTimes = 0;
- }
- Console.WriteLine("The most frequent number is {0}. It appears {1} times.", totalMostFrequent, maxTimes);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement