简体   繁体   中英

inputting an array and finding if a number is in that array (all using recursion) c++

#include <iostream>
#include <cstdlib>


using std:: cin;
using std:: cout;
using std:: endl;

const int N=10;

void readarray(int array[], int N);
int find_num(int array[], int size);


int main ()
{
   int array[N];
   readarray (array, N);
   cout << find_num(array, N);

   return EXIT_SUCCESS;
}



 void readarray(int array[], int N)
 // this function is for inputting an array also using recursion
 {
   int i=0;
   if (i < N)
   {
        cin >> array[i];
        readarray(array+1, N-1);
   }
 }


 int find_num(int array[], int size)
 // this function is for checking if a number is in the array that 
 // was inputted
 {
    int n;
    cin >> n;

    if (n==array[0])
        return 1;
    else if (n!=array[0]){
        find_num(array+1, size-1);
            return 1;
    }
    else return 0;
  }

Obviously, the whole point of the program is to only use recursion. I am having a problem with the the second function which is supposed to be checking if a number is found in the array or not. If the number has been found in the array then the output will be 1 if not then it should be 0. The problem is, it seems like it is taking more inputs than it should be and always outputs the number 1 (regardless if the number was found or not). I believe I am missing a small step. I do also want to ask if the void function is correct as well (seems like its working fine to me). thanks.

There are two termination criteria for your recursive function.

  1. If you reache the end of the array, you haven't found the number n and return 0 .

  2. If you found the number n return 1 .

If you not reache the end of the array and the number was not found, call your function rcursive, get the result and return it.

Apart from this the number you are searching for has to be an input to your function find_num . You don`t want to ask for a number again and again.

int find_num(int n, int array[], int size)
{
    if ( size == 0 )
        return 0; // end of array, n was not found
    if ( n == array[0] )
        return 1; // n was found
    return find_num( n, array+1, size-1 ); // test next element of array
}

void readarray(int array[], int N)
{ 
    if ( N > 0 )
    {
        cin >> array[0];
        readarray( array+1, N-1 );
    }
}

int main ()
{
   int array[N];
   readarray( array, N );

   int n;
   cin >> n;
   cout << find_num( n, array, N );

   return EXIT_SUCCESS;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM