DEV Community

Cover image for Linear Search .Net
Sukhpinder Singh
Sukhpinder Singh

Posted on • Originally published at singhsukhpinder.Medium

Linear Search .Net

Searches particular value within a data structure.


Linear search checks each element in the list until a match is found or until it reaches the end.

Linear Search Function

Consider the linear function as “LinearSearch(arr,value)”

  • where arr is the array to search inside of
  • where value is the element, we are searching for in array “arr.”


  • Returns -1, if element not found
  • Returns the index of an array element, where arr[index]=value

Pseudo Code

  • Set answer to -1
  • For each index from index=1 to n (where n is the last index of arr)
  • If arr[index]=value, then set the answer to the index value
  • Return the value of the answer as output

Getting Started

The article demonstrates the use of linear search inside an integer array in a console application.

Firstly, let's write code for linear function as per pseudo code. Iterate over an integer array and returns array index where a[i]==x and -1 if not found.

Finally, let’s write code to utilize the linear function.

  1. Prepare an integer array with the following elements. 1, 4, 5, 7, 9, 22
  2. Display all elements on the console window.
  3. Take user input from the console which element to search in an array.
  4. Call LinearSearchfunction created with both array and element to search.
  5. If index!=-1 then output “Element {value} found at index {index}.”
  6. Else then output “Element not found.”

Case 1 Output

    Current rray Elements 1 , 4 , 5 , 7 , 9 , 22
    Enter the element to be searched
    Element 5 found at index 2
Enter fullscreen mode Exit fullscreen mode

Case 2 Output

    Current rray Elements 1 , 4 , 5 , 7 , 9 , 22
    Enter the element to be searched
    Element not found
Enter fullscreen mode Exit fullscreen mode

Github Repo

Please find below the GitHub repository demonstrate linear search using the .Net 5 console application.
Linear Search

Thank you for reading, and I hope you liked the article. Please provide your
feedback in the comment section.

Follow me on C# Publication,


Top comments (0)