In my previous blogs, I have calculated factorial of a given number using while,do-while and for loop.Today I will calculate factorial using function.
Below is the source code of this program.
Below is the source code of this program.
Source code
#include<iostream>
#include<conio.h>
using namespace std;
void factorial(int n);
main()
{
int n;
cout<<"Enter any number:";
cin>>n;
factorial(n);//function call
getch();
}
void factorial(int n)
{
int c,f=1;
for( c=1;c<=n;c++)
{
f=f*c;
}
cout<<"Factorial="<<f;
}
#include<conio.h>
using namespace std;
void factorial(int n);
main()
{
int n;
cout<<"Enter any number:";
cin>>n;
factorial(n);//function call
getch();
}
void factorial(int n)
{
int c,f=1;
for( c=1;c<=n;c++)
{
f=f*c;
}
cout<<"Factorial="<<f;
}
Output
Explanation:
Line #4:
It is function declaration with a parameter and no argument.
Line #10:
It is the function call with a parameter.
Line #13:
It is the function definition which tells what a function actually does.It is also without argument and with a parameter.
Logic of factorial
.For your revision,I will explain what a factorial actually is.
The factorial of 4 can be calculated as
4!=4*3*2*1=24
In the same way,factorial of 5 can be calculated as
5!=5*4
=20
=20*3
=60
=60*2
=120
=120*1
=120
The factorial of 4 can be calculated as
4!=4*3*2*1=24
In the same way,factorial of 5 can be calculated as
5!=5*4
=20
=20*3
=60
=60*2
=120
=120*1
=120
No comments:
Post a Comment