Last active
October 22, 2016 11:46
-
-
Save taisyo7333/6a646e2119605c1e4865eb969feb16e6 to your computer and use it in GitHub Desktop.
C++ Factorial loop recursion
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> | |
int RecursiveFactorial(int number) | |
{ | |
if (number < 0) throw std::invalid_argument("Negative number is not allowed."); | |
if (number == 0) return 1; | |
return number * RecursiveFactorial(number - 1); | |
} | |
int LoopedFactorial(int number) | |
{ | |
if (number < 0) throw std::invalid_argument("Negative number is not allowed."); | |
int total = 1; | |
for (int n = number; n >= 0; n--) | |
{ | |
if (n == 0) total *= 1; | |
else total *= n; | |
} | |
return total; | |
} | |
int main() | |
{ | |
for (int i = 0; i < 5; i++) | |
{ | |
std::cout << i << "! = " << LoopedFactorial(i) << " , " << RecursiveFactorial(i) << std::endl; | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment