• closed by
623 views
0 0 votes
closed with the note: Undefined Behavior
#include<iostream>
using namespace std;
int f(int &x, int c)

{

    c = c - 1;

    if (c == 0)
        return 1;

    x = x + 1;

    return f(x, c) * x;
}
int main()
{
    int p = 5;
    cout << f(p,p) << endl;
    return 0;
}



The above given code prints 6561 but while solving i am getting 3024 as answer.I have tried multiple times but my answer is still same.

2 Answers

2 2 votes
First thing is the difference you are seeing is because of passing x as reference not by value, if you pass x as value to the above function you will get 3024 since you are passing it by reference it is taking final answer of the recursion which is "9" and multiplying it by itself and hence it prints 6561.
1 1 vote
At statement, return f(x, c) * x;

In the recursive tree, don't fix the value of x initially. First go through the recursive function call till the base case.
 

F(5, 5)

   |c = 4, x = 6

F(6, 4)

   | c = 3, x = 7

F(7, 3)

   |c = 2, x = 8

F(8, 2)

   | c = 1, x = 9

F(9, 1)

   | c = 0, return 1;

 

Now, x = 9;

 

F(9, 1) = 1, Multiply it with x now and return. =>9

F(8, 2) = 9, Multiply it with x now and return => 81

........
Position:
Show:

Related questions

3 3 votes
2 answers 2 answers
782
782 views
harshitraj12 asked Jun 23, 2024
782 views
Find Output of below Code#include<stdio.h>int sum(int n) { n = 3; if (n == 2) return 2; return sum(n-1)*n ;}int main() { printf("%d\n", sum(5) ); return 0}
1 1 vote
2 answers 2 answers
758
758 views
Debargha Mitra Roy asked Apr 10, 2024
758 views
What is the output of the below code?#include <stdio.h void main() { static int var = 5; printf("%d ", var ); if (var) main(); }a. 1 2 3 4 5b. 1c. 5 4 3 2 1d. Error
3 3 votes
3 3 answers
2.1k
2.1k views
Laxman Ghanchi asked May 19, 2023
2,073 views
#include<stdio.h void print(int n) { printf("Hello "); if(n++ == 0) return ; print(n); n++; } int main() { void print(); print(-4); }How many times printf execute?? And H...
1 1 vote
1 1 answer
1.1k
1.1k views
Laxman Ghanchi asked May 19, 2023
1,090 views
#include<stdio.h>void print(int n){ printf("Hello "); if(n++ == 0) return ; print(n); n++;}int main(){ void print(); print(-4);}