As soon as you run this program you will see a prompt asking you to enter a value. That is because random values from 1 – 20 were already assigned to the declared array. Now, you are simply ready to ask the program if the value that you enter is present in the array or not. In addition to telling you if it is there, it will also count the number of times a value appears if it appears.
Note, you can generate a value greater than 20, by replacing the number 20 within rn.Next(20) to higher value.
using System;
using System.Collections.Generic;
using System.Text;
namespace pe7_7
{
/*This program will utilize the
* array binary search. It will
* also utlize sort. */
class BinarySearch
{
static void Main(string[] args)
{
int[] fVal = new int[15];
Random rn = new Random();
int ui;
for(int k=0; k<15; k++)
{
fVal[k] = rn.Next(20);
}
Array.Sort(fVal);
Console.Write("Search for a value: ");
ui = Convert.ToInt32(Console.ReadLine());
//the UserSearch() method uses the BinarySearch method
//from the Array class to determine if the value exists
UserSearch(ui, fVal);
Console.ReadLine();
}
static void UserSearch(int ui, int[] fVal)
{
int counter = 0;
foreach (int i in fVal)
{
if (i == ui)
{
counter++;
}
}//end foreach
if (Array.BinarySearch(fVal, ui) > -1)
{
Console.Write("Using Binary Search, the value {0} exists in the array. \n" +
"It appears {1} time(s) in the array.", ui, counter);
}
else
{
Console.Write("Using Binary Search, the value {0} does not exists in array.", ui);
}
}
}
}