Write a program in C# to search an element in a array using Linear Search.
Following is the simple C# code :
Following is the simple C# code :
class Lab { static void Main(string[] args) { int SIZE = 1000; int[] myarray = new int[SIZE]; Console.WriteLine("How many number of elements you want in the array ?"); string arraylenth = Console.ReadLine(); int number = Int32.Parse(arraylenth); Console.WriteLine("-------------------------"); Console.WriteLine("Enter array elements \n"); for (int i = 0; i < number; i++) { string num = Console.ReadLine(); myarray[i] = Int32.Parse(num); } Console.WriteLine("-------------------------"); Console.WriteLine("Enter Search element\n"); string Search = Console.ReadLine(); int SearchNumber = Int32.Parse(Search); for (int i = 0; i < number; i++) { if (myarray[i] == SearchNumber) { Console.WriteLine("-------------------------"); Console.WriteLine("Search successful"); Console.WriteLine("Element {0} found at location {1}\n", SearchNumber, i + 1); Console.ReadLine(); return; } } Console.WriteLine("Search unsuccessful"); Console.ReadLine(); } }
Output:-
How many number of elements you want in the array ? 10 ------------------------- Enter array elements 45 68 12 15 3 5 2 9 4 45 ------------------------- Enter Search element 45 ------------------------- Search successful Element 45 found at location 1
No comments:
Post a Comment
Note: only a member of this blog may post a comment.