Use a for statement to evaluate the factorials of the integers from 1 to 5. Print the results in tabular format. - C++ Statement

C++ examples for Statement:for

Description

Use a for statement to evaluate the factorials of the integers from 1 to 5. Print the results in tabular format.

Demo Code

#include <iostream>

int factorial(int);

int main(int argc, const char *argv[]) {
    std::cout << "Factorials of 1 to 5\n" << std::endl;

    for (int i = 1; i <= 5; i++) {
        printf("%d\t%d\n", i, factorial(i));
    }//from  w  w w. ja  v  a  2s.  com
    return 0;
}
// n! = n * (n-1) * (n-2) * (n-3) * ... * 1
int factorial(int n) {
    int factorial = 1;

    for (int i = 1; i <= n; i++) {
        factorial *= n;
    }

    return factorial;
}

Result


Related Tutorials