Recursion using function in C++


The program is calculating the factorial of a number using recursion. The factorial function takes an integer n as input and returns its factorial. If n is greater than 1, the function calls itself with n-1 as input and multiplies the result with n to get the factorial of n. If n is 1 or less, it returns 1, which is the factorial of 0 and 1. In the main function, it takes the input number from the user, calls the factorial function to calculate its factorial, and displays the result

Source Code

#include <iostream>
using namespace std;
int factorial(int);
int main()
{
    int n,result;
    cout<<"Enter a number: ";
    cin>>n;
    result=factorial(n);
    cout<<"Factorial of "<<n<<" = "<<result;
    return 0;
}
int factorial(int n)
{
    if(n>1)
    {
        return n*factorial(n-1);
    }
    else
    {
        return 1;
    }
}
To download raw file Click Here

Output

Enter a number: 10
Factorial of 10 = 3628800

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples