DEV Community

Ayush Ranjan
Ayush Ranjan

Posted on

Recursion in c++

#include <iostream>
using namespace std;

int factorial(int n) {
    cout << n << endl;
    if (n == 0) {
        return 1;
    int smallOutput = factorial(n - 1);
    return n * smallOutput;

int main() {
    int n;
    cin >> n;
    int output = factorial(n);
    cout << output << endl;
Enter fullscreen mode Exit fullscreen mode

let's break down the code.

In this code we are goin code factorial, first of fall we are taking int value after that in the next step we are printing initial value and in next step we are taking n == 0 and returning the 1, because if we don't than when the value of n = 0 and it's return 0 than we will not get the correct output what we want as well in next step as we saw there we again calling factorial that all goin to again run it from start until value become zero after n will become zero the function will go further next step and it's multiply to n one by one like :

fact(1) n = 1, n * 1
than fact(2) n = 2, n * 1 * 2
so on,
after getting value from them the they will be out of memory

Discussion (0)