0

When calling the function f4 how is the function returning 6? i really cant figure out how the function operates shouldnt it just return 1? because of (n-1)

  #include <iostream>
    #include<cmath>
    #include<fstream>
    using namespace std;
    int x = 3;
    void f1(int, int &);

    int f4(int);

    int main()

    { 
        int x = 5; int y = 10;
        f1(x, y); 
        cout << x << "\t" << y << endl;
        x = 15; y = 20;
        f1(x++, x); 


        cout << x << "\t" << y << endl; 
        x = 3;
        cout << f4(x) << endl; 

        system("pause");
        return 0;
    }

    void f1(int a, int &b)
    {
        a *= 2; b += x;
        cout << a << "\t" << b << endl;
    }

    int f4(int n) {
        if (n == 1 || n == 0) 
            return n;
        else
            return n + f4(n - 1);
    }

2 Answers 2

2

The f4 function is recursive. This calling with a number other than 1 or 0 will make it recurse. You call it with 3, so the compiler (simplified) sees

f4(3) => 3 + f4(2) => 3 + 2 + f4(1) => 3 + 2 + 1 => 5 + 1 => 6
2

recursion in a nutshell..

   int f4(int n) {
        if (n == 1 || n == 0) 
            return n;
        else
            return n + f4(n - 1);
 }

Your code states that when n is 1 or 0 just return n, otherwise add n to the result of the function.

that sets up a recursive stack where the first call n = 3 and it recurses. on the next call n = 2 and it recurses. on the next call n = 1 and it returns as well as the rest of the stack leading to 1 + 2 + 3 which is 6.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.