Factorial Program using Loop
Factorial Program in C++ using loop.
- #include <iostream>
- using namespace std;
- int main()
- {
- int i,fact=1,number;
- cout<<"Enter any Number: ";
- cin>>number;
- for(i=1;i<=number;i++){
- fact=fact*i;
- }
- cout<<"Factorial of " <<number<<" is: "<<fact<<endl;
- return 0;
- }
Output:
Enter any Number: 5
Factorial of 5 is: 120
Factorial Program using Recursion
Factorial program in C++ using recursion.
- #include<iostream>
- using namespace std;
- int main()
- {
- int factorial(int);
- int fact, value;
- cout<<"Enter any number: ";
- cin>> value;
- fact = factorial(value);
- cout<<"Factorial of a number is: "<<fact <<endl;
- return 0;
- }
- int factorial(int n)
- {
- if(n<0)
- return(-1);
- if(n==0)
- return(1);
- else
- {
- return ( n*factorial(n-1) );
- }
- }
Output:
Enter any number: 6
Factorial of a number is: 720
0 Comments
you can ask question related to this post