Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Linear search programming in C#

The below code explains linear search.
The user will have to add the total numbers want to add in array and the single number that is needed to be searched.

  1. using System;
  2.  
  3. namespace forgetCode
  4. {
  5. class Program
  6. {
  7. public static void Main()
  8. {
  9. int[] a = new int[100];
  10. Console.WriteLine("Enter number of elements you want to hold in the array ?");
  11. string s = Console.ReadLine();
  12. int x = Int32.Parse(s);
  13. Console.WriteLine("-------------------------");
  14. Console.WriteLine("\n Enter array elements \n");
  15. for (int i = 0; i < x; i++)
  16. {
  17. string s1 = Console.ReadLine();
  18. a[i] = Int32.Parse(s1);
  19. }
  20. Console.WriteLine("-------------------------");
  21. Console.WriteLine("Enter Search element\n");
  22. string s3 = Console.ReadLine();
  23. int x2 = Int32.Parse(s3);
  24. for (int i = 0; i < x; i++)
  25. {
  26. if (a[i] == x2)
  27. {
  28. Console.WriteLine("-------------------------");
  29. Console.WriteLine("Search successful");
  30. Console.WriteLine("Element {0} found at location {1}\n", x2, i + 1);
  31. return;
  32. }
  33. }
  34. Console.WriteLine("Search unsuccessful");
  35. }
  36. }
  37.  
  38. }


Output:

Iteration 1:


Enter number of elements you want to hold in the array ?
4
-------------------------

Enter array elements

12
22
33
46
-------------------------
Enter Search element

33
-------------------------
Search successful
Element 33 found at location 3



Iteration 2:

Enter number of elements you want to hold in the array ?
4
-------------------------

Enter array elements

23
45
66
45
-------------------------
Enter Search element

22
Search unsuccessful

...