In this blog, we will create a c# program that takes input from the user and check-in predefine array to check how many times that number occurs in that array.
- using System;
- using System.Linq;
- namespace CheckOccurrenceOfNumberInArray
- {
- class Program
- {
- static void Main(string[] args)
- {
- int[] array = { 1, 20, 15, 23, 15, 14, 26, 188,175,12, 36, 78, 15, 3, 5, 91, 822, 100, 1202, 78, 95, 12, 123, 12, 14, 25, 36, 15, 36, 95, 45, 10, 20, 30, 04, 50, 40, 60, 70, 80, 90, 104 };
- Console.WriteLine("Your Array...");
- for (int i = 0; i < array.Length; i++)
- {
- Console.Write(array[i] + " ");
- }
- Console.WriteLine("\n\n");
- Console.Write("Enter number to check occurrence : ");
- int number = Convert.ToInt32(Console.ReadLine());
-
- int occurrences = array.Count(x => x == number);
- Console.WriteLine("Occurrence of {0} in given array is {1}", number, occurrences);
- Console.ReadKey();
- }
- }
- }
Explanation
- In this program, first we declare an array of integer types and then print it to show the user.
- Then take input from the user.
- Check that input with our array using the LINQ count method and pass expression in that method also that element is equal to the given number.
Output 1
Output 2
Output 3