55.1k views
2 votes
Write a c++ program to calculate the factorial of a number

2 Answers

4 votes

CODE

#include <iostream>

using namespace std;

int main() {

// Declare the variables

int n = 19;

long int factorial = 1;

// Each time, the factorial multiplies by integers from 1 to the maximum number.

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

factorial = factorial * i;

}

// Display the factorial

cout << factorial;

return 0;

}

EXPLANATION

Declare n and factorial as integers and long integers.

The "for loop" runs from 1 to the maximum number and increments by 1. The factorial multiplies each time by integers from 1 to n.

Print the factorial.

User Thibaud Colas
by
3.5k points
2 votes

Answer:

#include <iostream>

int factorial(int n) {

return (n > 1) ? n*factorial(n-1) : 1;

}

int main() {

std::cout << factorial(5);

}

Step-by-step explanation:

Above is an approach using recursion.

It will output 120, which is 5! = 5*4*3*2*1

User Jonatan Dragon
by
3.2k points