Write a program in C++ which calculates the factorial of a given number using user defined function.
Program Code:
#include <iostream>
using namespace std;
// user defined function named factorial with one argument
int factorial (int a)
{
if (a > 1)
{
return (a * factorial (a-1));
}
else
{
return (1);
}
}
int main()
{
int num;
cout << "Enter a number to find the factorial : ";
cin >>num;
cout<<endl;
cout << "!" << num << " = " << factorial (num);// function call
return 0;
}
The program output is tested on www.jdoodle.com
Output:
Enter a number to find the factorial : 5
!5 = 120
Thanks
Mukesh Rajput
Post A Comment:
0 comments: