Recursive functions

closed account (EAp4z8AR)
Why do I keep getting a segmentation fault?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  int main()
{
    int x;
    
    cout << "Enter a number greater than or equal to 0: ";
    cin >> x;
    
    if (x>=0)
    {
        f(x);
    }
    
    while (x<0)
    {
        cout << "Please enter a valid number!\n";
        cout << "Enter a number greater than or equal to 0: ";
        cin >> x;
        
        
    }
}


int f(int n)
{
    
    if (n==0)
    {
        return f(n)=5; //base case
    }
    
    else
    {
        f(n) = 2*f(n-1)-3; //recursive case
    }
}
Last edited on
The function f says it returns something. But it doesn't. If a function claims it will return something, it must return something.

f(0)==5; //base case
This makes no sense at all.

f(n) == 2*f(n-1)-3; //recursive case
This also makes no sense.

Last edited on
closed account (EAp4z8AR)
Sorry about my mistake I am new to this.

But the objective is that the user enters a number suppose the number 8. The recursive function has to run from f(0) to f(8), and the base case that I was given is that f(0) = 5. And that is supposed to be used to find f(1) like this f(1) = 2*f(1-1)-3 which simplifies to f(1) = 2*f(0)-3.
closed account (EAp4z8AR)
Im thinking that i need to use a for loop, but im not sure how to use it with f(0) = 5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

int f(int n)
{
    if (n == 0)
        return 5;  // base case
    else
        return 2 * f(n-1) - 3;  // recursive case
}

int main()
{
    int x = 0;
    while (true)
    {
        std::cout << "Enter a number greater than or equal to 0: ";
        std::cin >> x;
        if (x >= 0) break;    
        std::cout << "Please enter a valid number!\n";
    }
    
    std::cout << f(x) << '\n';
}

Topic archived. No new replies allowed.