lab12hw-factorial-soln - result = result * i; } return...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
// Programmer: Doug Hogan // Section: N/A // Program: Solution to this homework problem: // http://php.scripts.psu.edu/djh300/cmpsc201/lab12hw-function.htm // Date: October 12, 2008 // Description: This program computes the factorial using a function. #include <iostream> using namespace std; int Factorial(int x) // PRE: x >= 0 // POST: FCTVAL == x!, i.e. the factorial of x { int result = 1; // factorial of x; starts at 1 // as we'll multiply by it and // as 0! = 1 for(int i = 1; i <= x; i++) // multiply result by all numbers { // b/w 1 and x to find factorial
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: result = result * i; } return result; } int main() { int inputNumber; // number whose factorial we want cout << "Enter a positive integer to get its factorial: "; cin >> inputNumber; if(inputNumber >= 0) // make sure inputNumber meets { // precondition before call cout << inputNumber << "! = " << Factorial(inputNumber) << endl; // use method to compute // the factorial } else // error: precondition failed { cout << "Factorial is not defined for " << "negative numbers. Try again." << endl; } return 0; }...
View Full Document

This document was uploaded on 02/10/2011.

Ask a homework question - tutors are online