137k views
1 vote
Write a program that lets a user enter n and that outputs n! (meaning n*(n-1)*(n-2)*...*2*1). hint: initialize a variable totalvalue to n, and use a loop variable i that counts from n-1 down to 1.

User Cooleronie
by
7.5k points

1 Answer

5 votes
// This code snippet calculates n! and stores the answer in the variable p.
// Handle 0! = 1 separately.
if (n==0) {
p = 1;
}
else {
// Initialize p = n
p = n;

// While loop
while (n>1) {
p = p*(n-1);
n = n-1;
}
}

User PatrickD
by
7.7k points