//non-recursive factorial program //jleblanc 2.4.06 //PAC II //Description: This program returns the factorial of an integer using each //of the 3 iterative loop structures. for n! when n<1, function returns 1. /* 1) We spoke in class about "recursive" functions. Examine the factorial program (sent separately). Re-write the factorial function non-recursively, using a loop instead. Write it three times, once with each C looping structure. */ #include int factorial_for(int n) { int product=1; int x; for(x=1; x<=n; x++) { product=product*x; } return product; } int factorial_while(int n) { int product=1; while ( n > 0) { product=product*n; n=n-1; } return product; } int factorial_dowhile(int n) { int product=1; do { product=product*n; n=n-1; } while ( n > 0); if( product > 0) {return product;} else {return 1;} } void main() { int input, answer; printf(" Welcome to the factorial calculator \n"); printf(" Please enter the value: "); scanf("%d", &input); //Note if I enter say .5, the program pauses and then just quits answer=factorial_for(input); printf("\n Using a For loop, the factorial of %2d is %6d\n", input, answer); answer=factorial_while(input); printf(" Using a While loop, the factorial of %2d is %6d\n", input, answer); answer=factorial_dowhile(input); printf(" Using a Do While loop, the factorial of %2d is %6d\n", input, answer); }