C++ Linear search

Introduction

Linear search is a simple search algorithm that searches for a target value within an array.
It compares each element of the array to the target value until a match is found or the whole array has been searched.


Source: geeksforgeeks

Code - Linear search

#include <iostream>
using namespace std;

int main() {
	int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};		// array of 10 elements
	int target;
	cout << "Enter a number to search: ";
	cin >> target;
	for(int i=0; i<10; i++) {		// loop through the array, i is the index from 0 to 9
		if(arr[i] == target) {				// if element is equal to target
			cout << "Found at index " << i << endl;
		}
	}
	cout << "Not found" << endl;
}
	

Task

Modify the above code:
1. Only print "Found" or "Not found" once.
2. Improve the efficiency of the search algorithm.
Hints: Does the loop really need to go through all the elements of the array?

Reference

w3schools