Advertisement
tvarbanov

CSharp2-03-04

Jan 3rd, 2014
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.71 KB | None | 0 0
  1. using System;
  2.  
  3. namespace NumberInArray
  4. {
  5.     public class NumberInArray
  6.     {
  7.         //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.
  8.  
  9.         public static int CheckNum(int num,int[] numArr)
  10.         {
  11.             int counter = 0;
  12.             for (int i = 0; i < numArr.Length; i++)
  13.             {
  14.                 if (numArr[i] == num)
  15.                 {
  16.                     counter++;
  17.                 }
  18.             }
  19.             return counter;
  20.         }
  21.  
  22.         static void Main()
  23.         {
  24.  
  25.             Console.Write("Enter the number you are looking for : ");
  26.             int num = int.Parse(Console.ReadLine());
  27.             Console.WriteLine("Enter the numbers for the array separated only by comma(,)");
  28.             string nums = Console.ReadLine();
  29.             //Convert string to int array
  30.             int[] arrayNums = new int[nums.Length/2+1]; //Half of the lenght is filled by commas + last digit which is not followed with comma
  31.             int arrCount = 0; //int array counter
  32.             //Fill the int array from the string variable
  33.             for (int i = 0; i < nums.Length; i++)
  34.             {
  35.                 if (nums[i] == ',') // if its comma skips the loop
  36.                 {
  37.                     continue;
  38.                 }
  39.                 else
  40.                 {
  41.                     arrayNums[arrCount] = nums[i] - 48;
  42.                     arrCount++; // if number is stored in the int array the counter increase
  43.                 }
  44.             }
  45.  
  46.             Console.WriteLine("The number {0} is present {1} times in the array!",num,CheckNum(num,arrayNums));
  47.  
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement