#include using namespace std; /** * Find the index of the first occurrence of * x in arr which is of size n. * * /param x The value to look for in arr. * /param n The size of the array arr. * /param arr The array to search through. * * /return The index in the array where x first appears * or -1 if it does not appear. */ int foo(int arr[], int x, int n) { int lastValue = arr[n-1]; // store the last value arr[n-1] = x; // set the last value to x int i=0; while (arr[i] != x) { i++; } if ((i == n-1) && // we did not find x before the end of the array (lastValue != x)) { // then x was not contained in arr i = -1; // so we return -1 } arr[n-1] = lastValue; // leave the array as we got it. return i; } int main() { const int N = 20; int arr[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int x = 10; cout << endl << "element " << x << " is first found in our array at position " << foo(arr, x, N) << endl; x = 11; cout << endl << "element " << x << " is first found in our array at position " << foo(arr, x, N) << endl << endl; return 0; }