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 267 views
2 answers 136 views
1 answer 245 views
1 answer 229 views
2 answers 258 views
258 views asked May 7, 2014 by avibootz
1 answer 90 views
1 answer 161 views
...