Group
Search and Sort Algorithms in C++
Objective
Write a C++ program that performs a linear search to find an element in an array. The function should return the index of the element if found, or -1 if the element is not in the array. Implement this search algorithm and test it with a sample array.
Implement a linear search algorithm.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the input-output stream library
using namespace std;
// Function to perform linear search on an array
int linearSearch(int arr[], int size, int target) {
// Loop through each element in the array
for (int i = 0; i < size; i++) {
if (arr[i] == target) { // Check if the current element matches the target
return i; // Return the index of the target element if found
}
}
return -1; // Return -1 if the target element is not found in the array
}
int main() {
// Define an array of integers
int numbers[] = {15, 27, 38, 49, 56, 72, 91};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the number of elements
// Define the target element to search for
int target = 49;
// Call the linearSearch function
int result = linearSearch(numbers, size, target);
// Check if the target was found and display the result
if (result != -1) {
cout << "Element found at index: " << result << endl; // Element found, display its index
} else {
cout << "Element not found in the array." << endl; // Element not found, display message
}
return 0; // End of the program
}
Output
Element found at index: 3