0

I had to write a code for checking whether a number is given in the array or not using recursion. But when I run my code, it just asks for a number and exits the program upon entering the number.

#include <bits/stdc++.h>
using namespace std;

int check(int *arr, int n, int x, int i)
{
    if (arr[i] == x)
    {
        return 1;
    }
    else if (i == n - 1)
    {
        return 0;
    }else{
    return  check(arr, n, x, i++);
    }
}

int main()
{
    int arr[8] = {4, 12, 54, 14, 3, 8, 6, 1};
    int x;
    cout << "Enter target value: ";
    cin >> x;
    if (check(arr, 8, x, 0) == 0)
    {
        cout << "No";
    }
    else
    {
        cout << "Yes";
    }
    return 0;
}

As said earlier , I wanted to print "Yes" if the given number is present in the array and "No" if the number is not present in the array.

  • 1
    You have an infinite recursion here; `check(arr, n, x, i++)` is calling the function with exactly the same parameters it was originally called with. (`i` would get incremented afterwards, but there *is no* afterwards because the recursion never terminates.). Use `++i` instead so that you're actually passing the modified value. – jasonharper Jun 29 '23 at 01:44
  • The code starts with [`#include `](https://stackoverflow.com/q/31816095/1458097) and [`using namespace std;`](https://stackoverflow.com/q/1452721/1458097), so I didn't bother to read any further, sorry. – heap underrun Jun 29 '23 at 01:44

0 Answers0