Create an array of random integers and search array sequentially. - CSharp Language Basics

CSharp examples for Language Basics:Array

Description

Create an array of random integers and search array sequentially.

Demo Code

using System;//from  www.j av  a2s .co m
public class MainClass
{
   static void Main()
   {
      var generator = new Random();
      var data = new int[10];
      // fill array with random ints in range 10-99
      for (var i = 0; i < data.Length; ++i)
      {
         data[i] = generator.Next(10, 100);
      }
      Console.WriteLine(string.Join(" ", data) + "\n"); // display array
      Console.Write("Enter an integer value (-1 to quit): ");
      var searchInt = int.Parse(Console.ReadLine());
      while (searchInt != -1)
      {
         int position = LinearSearch(data, searchInt);
         if (position != -1) // integer was found
         {
            Console.WriteLine($"The integer {searchInt} was found in " + $"position {position}.\n");
         }
         else // integer was not found
         {
            Console.WriteLine($"The integer {searchInt} was not found.\n");
         }
         Console.Write("Enter an integer value (-1 to quit): ");
         searchInt = int.Parse(Console.ReadLine());
      }
   }
   public static int LinearSearch(int[] values, int searchKey)
   {
      for (var index = 0; index < values.Length; ++index)
      {
         if (values[index] == searchKey)
         {
            return index; // return the element's index
         }
      }
      return -1; // integer was not found
   }
}

Result


Related Tutorials