How to use Call By Reference In C++

Below is the C++ program to find the factorial of a given number using call by reference:

C++




// C++ program to find the factorial
// of a given number using call
// by reference method
#include<iostream>
using namespace std;
 
// Function to find factorial
void factorial(int n, int *f)
{
    int i;
    for(i = n; i >= 1; i--)
        *f = (*f) * i;
}
 
// Driver code
int main()
{
    int num = 5, fact = 1;
   
    factorial(num, &fact);
    cout << "Factorial of " <<
             num << " is "<<
             fact;
    return 0;
}


Output

Factorial of 5 is 120


C++ Program To Find Factorial Of A Number

The Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n. For example, the factorial of 6 is 6*5*4*3*2*1 which is 720. 

 

Similar Reads

Recursive Solution

Factorial can be calculated using the following recursive formula....

Iterative Solution

...

Using Ternary Operator

Factorial can also be calculated iteratively as recursion can be costly for large numbers. Here we have shown the iterative approach using both for and while loops....

Using Call By Reference

...

Contact Us