How to calculate factorial of a number in C++

2 Answers

0 votes
#include <iostream>

int factorial(int n) {
    int result = 1;
    while (n > 1)
        result *= n--;
    return result;
}

int main() {
    std::cout << factorial(6) << " ";
    
    return 0;
}



/*
run:

720  

*/

 



answered May 7, 2021 by avibootz
0 votes
#include <iostream>

int factorial(int n) {
   return (n==1 || n==0) ? 1 : n * factorial(n - 1);
}

int main() {
    std::cout << factorial(6) << " ";
    
    return 0;
}



/*
run:

720  

*/

 



answered May 7, 2021 by avibootz

Related questions

2 answers 271 views
2 answers 147 views
1 answer 251 views
1 answer 95 views
1 answer 177 views
2 answers 237 views
1 answer 237 views
...