Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //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)
- using System;
- class Program
- {
- static void Main(string[] args)
- {
- //int[] array = { 2, 2, 1, 4, 2, 3, 2, 4, 1, 2, 4, 2, 2 };
- Console.WriteLine("Enter the array's lenght:");
- int size = int.Parse(Console.ReadLine());
- int[] array = new int[size];
- //Entering the values of the array from the console
- for (int i = 0; i < array.Length; i++)
- {
- Console.Write("array[{0}] = ", i);
- array[i] = int.Parse(Console.ReadLine());
- }
- //Calculating the most frequent number in the sequence
- int frequency = 0;
- int maxFrequency = 0;
- int mostFreqNum = 0;
- for (int i = 0; i < array.Length; i++)
- {
- frequency = 1;
- for (int j = i + 1; j < array.Length; j++)
- {
- if (array[i] == array[j])
- {
- frequency++;
- }
- }
- if (frequency > maxFrequency)
- {
- maxFrequency = frequency;
- mostFreqNum = array[i];
- }
- }
- //Printing the result
- for (int i = 0; i < array.Length; i++)
- {
- if (i == 0)
- {
- Console.Write("{");
- }
- Console.Write("{0}, ", array[i]);
- if (i == array.Length - 1)
- {
- Console.Write("}");
- }
- }
- Console.Write(" ----> ");
- Console.Write("{0} ({1} times)", mostFreqNum, maxFrequency);
- Console.WriteLine();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement