Use recursive function to do a linear search on the array. - C++ Function

C++ examples for Function:Recursive Function

Description

Use recursive function to do a linear search on the array.

Demo Code

#include <iostream>

int linearSearch(int[], int, int);

int main(int argc, const char *argv[]) {
    const int ARRAY_SIZE = 100;

    int a[ARRAY_SIZE];
    int searchKey;

    for (int i = 0; i < ARRAY_SIZE; ++i) {
        a[i] = 2 * i;/*ww  w.  j  a  va2 s  .c  om*/
    }

    std::cout << "Enter integer search key: ";
    std::cin >> searchKey;

    int element = linearSearch(a, searchKey, ARRAY_SIZE);

    // display results
    if (element != -1)
        std::cout << "Found value in element " << element << std::endl;
    else
        std::cout << "Value not found" << std::endl;

    return 0;
}

int linearSearch(int array[], int key, int sizeOfArray) {
    --sizeOfArray;

    // not found
    if (sizeOfArray < 0) 
       return -1;

    if (array[sizeOfArray] == key) 
       return sizeOfArray;

    return linearSearch(array, key, sizeOfArray);
}

Result


Related Tutorials