Saturday, February 1, 2014

C++ Without Fear by Brian Overland - Exercise 04.01.01 - Corrected Code

If you are working through this book, before you look at the code, I encourage you to download the source files yourself, from here:
http://www.informit.com/store/c-plus-plus-without-fear-a-beginners-guide-that-makes-9780132673266

The source code is found in the Downloads tab, where you click on the word here. Do not click on the website link, as it goes to an unrelated website.

Study the code for this exercise after you have tried to work through it on your own. HINT, you will need to use a function! See if you can get it to work on your own. If you remain unable to do so, refer back to this post.

Here is the corrected Source Code:
#include <iostream>

using namespace std;

int factorial(int num);

int main() {
    int n;

    cout << "Enter a number and press ENTER: ";
    cin >> n;

    cout << "Function returned " << factorial(n) << endl;
    return 0;
}

int factorial(int n) {
    int product = 1;

    for (int i = 1; i <= n; i++)
        product = product * i;
    return product;
}


I will post any additional exercises or assignments that need correction as I work through the book.

No comments:

Post a Comment