Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- // 4. Write a method that counts how many times given number appears in given array.
- // Write a test program to check if the method is working correctly.
- class CountingNumberInArray
- {
- static void Main()
- {
- Console.WriteLine("How many elements do you want to have in the array? ");
- int n = int.Parse(Console.ReadLine());
- int[] arrayToCount = new int[n];
- // for random generator to fill the array
- Random rndGenerator = new Random();
- for (int i = 0; i < arrayToCount.Length; i++)
- {
- arrayToCount[i] = rndGenerator.Next(1, 100);
- }
- // for user input to fill the array
- //for (int i = 0; i < arrayToCount.Length; i++)
- //{
- // Console.Write("Elemеnt {0} = ", i+1);
- // arrayToCount[i] = int.Parse(Console.ReadLine());
- //}
- Console.WriteLine("Randomly generated array");
- foreach (var number in arrayToCount)
- {
- Console.Write(number + " ");
- }
- Dictionary<int, int> dict = CountingNumber(arrayToCount);
- Console.WriteLine();
- foreach (var pair in dict)
- {
- Console.WriteLine("The number {0} apears {1} time(s).", pair.Key, pair.Value);
- }
- }
- static Dictionary<int, int> CountingNumber(int[] array)
- {
- var dict = new Dictionary<int, int>();
- foreach (int value in array)
- {
- if (dict.ContainsKey(value))
- {
- dict[value]++;
- }
- else
- {
- dict.Add(value, 1);
- }
- }
- return dict;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement