49.8k views
3 votes
Write a program in C++ to implement linear search by using the
Array of 5 Elements in a class.

User Hungr
by
7.3k points

1 Answer

5 votes

Final answer:

The student is instructed to write a C++ program that performs a linear search in an array of 5 elements using a class. A code snippet demonstrates a class implementation of linear search and its usage in the main function.

Step-by-step explanation:

The student is asking to write a program in C++ that implements a linear search within an array of 5 elements. A linear search is a simple algorithm that checks each element in the array sequentially until the desired value is found or the end of the array is reached.

Here is an example of how to implement a linear search in a C++ class:

class LinearSearch {
public:
int search(int arr[], int n, int x) {
for (int i = 0; i < n; i++) {
if (arr[i] == x)
return i;
}
return -1;
}
};

int main() {
LinearSearch searchObj;
int arr[5] = {1, 3, 5, 7, 9};
int x = 7;
int index = searchObj.search(arr, 5, x);
if (index != -1)
cout << "Element found at index: " << index << endl;
else
cout << "Element not found." << endl;
return 0;
}

This program defines a class LinearSearch with a function search() that takes an array arr[], its size n, and the value to search for x. If the value is found, the function returns the index where it was found; if not, it returns -1. The main() function demonstrates the usage of the LinearSearch class with an example array and search value.

User Tahir Siddiqui
by
8.2k points