Answer:
#include <iostream>
#include <ctype.h>
#include <vector>
#include <algorithm>
using namespace std;
int findValue1(int* pArray, int nrElements, int value) {
for (int i = 0; i < nrElements; i++) {
if (pArray[i] == value) {
return i;
}
}
return -1;
}
void test1(int* pArray, int nrElements, int value) {
int index = findValue1(pArray, nrElements, value);
if (index >= 0) {
cout << value << " is found at index " << index << endl;
}
else {
cout << value << " is not in the array" << endl;
}
}
int findValue2(std::vector<int> vec, int value) {
std::vector<int>::iterator it = std::find(vec.begin(), vec.end(), value);
if (it != vec.end()) {
return it - vec.begin();
}
return -1;
}
void test2(std::vector<int> vec, int value) {
int index = findValue2(vec, value);
if (index >= 0) {
cout << value << " is found at index " << index << endl;
}
else {
cout << value << " is not in the array" << endl;
}
}
int main() {
int arr[] = { 4, 8, 15, 16, 23, 42 };
int nrElements = sizeof(arr) / sizeof(int);
test1(arr, nrElements, 0);
test1(arr, nrElements, 15);
test1(arr, nrElements, 42);
test1(arr, nrElements, 7);
std::vector<int> vec(std::begin(arr), std::end(arr));
test2(vec, 0);
test2(vec, 15);
test2(vec, 42);
test2(vec, 7);
}
Step-by-step explanation:
Here are two solutions. One old-school array approach, and a standard library (STL) alternative.