Related Articles
C/C++ Program for Linear Search
• Last Updated : 04 Dec, 2018

Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[].

## C/C++

 `#include ``using` `namespace` `std;`` ` `// Linearly search x in arr[].  If x is present then return its``// location,  otherwise return -1``int` `search(``int` `arr[], ``int` `n, ``int` `x)``{``    ``int` `i;``    ``for` `(i = 0; i < n; i++)``        ``if` `(arr[i] == x)``            ``return` `i;``    ``return` `-1;``}`` ` `// Driver code``int` `main()``{``    ``int` `arr[] = { 3, 4, 1, 7, 5 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);``    ``int` `x = 4;`` ` `    ``int` `index = search(arr, n, x);``    ``if` `(index == -1)``        ``cout << ``"Element is not present in the array"``;``    ``else``        ``cout << ``"Element found at position "` `<< index;`` ` `    ``return` `0;``}`
Output:
```Element found at position 1
```

The time complexity of the above algorithm is O(n).

Please refer complete article on Linear Search for more details!

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.

My Personal Notes arrow_drop_up