Advertisement
Hristo_B

Methods.CountNumberInArray

Jul 8th, 2013
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.12 KB | None | 0 0
  1. using System;
  2.  
  3. public class CountNumberInArray
  4. {
  5.     //Write a method that counts how many times given number appears in given array.
  6.     //Write a test program to check if the method is working correctly.
  7.  
  8.     public static int CountNumber(int[] arr, int number)
  9.     {
  10.         int counter = 0;
  11.         for (int i = 0; i < arr.Length; i++)
  12.         {
  13.             if (arr[i] == number)
  14.             {
  15.                 counter++;
  16.             }
  17.         }
  18.         return counter;
  19.     }
  20.  
  21.     public static void Main()
  22.     {
  23.         int[] arr = { 1, 2, 3, 25, 345345, 23, 4, 4, 6456, 4, 6, 3, 4, 4 };
  24.         Console.WriteLine("The array is: {0}",string.Join(", ", arr));
  25.         Console.WriteLine("Insert a number which you want to count!");
  26.         int searchedNumber = int.Parse(Console.ReadLine());
  27.         Console.WriteLine("Your number {0} appears {1} times in the array.", searchedNumber, CountNumber(arr, searchedNumber));
  28.  
  29.  
  30.         // In the next project named CountNumberUnitTests are the tests for this method, if you want to run them
  31.         //just right click and there you should see "Run Tests".
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement