Trap 7 - Factorial

◀ Trap 6 - Prime Number▶ Trap 8 - Divide
Amazon A program can contain bugs of many types. Some bugs are related to syntax and will cause the compiler to fail to compile. Other bugs are related to logic and need more thinking to fix.

The following program is supposed to accept an integer and output its factorial, but it contains several bugs. Track them down and fix them.
#include <iostream>
using namespace std;

int factorial(int n){
	int p=1;
	int i=n;
/* compute p = n * (n-1) * (n-2) * ... * 2 */
while(i>=2); { i--; p=*i; } return i; } int main(){ int input; cout<<"Please enter an integer: "; cin>>input; cout<<factorial(input)<<endl; return 0; }

Solution
First of all, this program will not even compile. A programmer with keen eyes would spot the error right away; in the while loop p=*i should be p*=i. This is a simple syntax error.

The second error is the semicolon after the while loop. The third error is i--; should be after p*=i, not before it.

Sometimes in writing a loop you may be confused about whether the index should be incremented first or after some other code. By carefully going through the loop, you should be able to figure out the order in a jiffy.
The last error is that p should be returned instead of i. What a function returns is also a common source of error. The variable p is what we want to return, not i. The following is the complete corrected program.
#include <iostream>
using namespace std; int factorial(int n){ int p=1; int i=n; /* compute p = n * (n-1) * (n-2) * ... * 2 */ while(i>=2) { p*=i; i--; } return p; } int main(){ int input; cout<<"Please enter an integer: "; cin>>input; cout<<factorial(input)<<endl; return 0; }
Next let’s look at what happens when the preconditions and postconditions of a function are not preserved!

◀ Trap 6 - Prime Number▶ Trap 8 - Divide

fShare
Questions? Let me know!