Last active
July 1, 2019 17:31
-
-
Save manojnaidu619/d0372c1c4e162d4ca290f22a25a7aa3a to your computer and use it in GitHub Desktop.
factorial in different ways in CPP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
int recursive_fact(int n){ | |
/* | |
ex: fact(n) = 1*2*3........*(n-1)*n | |
so, (fact(n-1)*n) Gives us the answer | |
*/ | |
if(n==0){return 1;}else{ | |
return recursive_fact(n-1)*n; | |
} | |
} | |
int using_for(int n){ | |
int fact = 1; | |
if(n==0){return 1;}else{ | |
for(int i=1;i<=n;i++){ | |
fact *= i; | |
} | |
return fact; | |
} | |
} | |
int using_while(int n){ | |
if(n==0){return 1;}else{ | |
int fact=1,i=1; | |
while(i <= n){ | |
fact *= i; | |
i++; | |
} | |
return fact; | |
} | |
} | |
int main(){ | |
int n = 3; | |
cout << recursive_fact(n) << endl; | |
cout << using_for(n) << endl; | |
cout << using_while(n) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment