Hi.
I started programming a couple of weeks ago. I'm going through that C++ Without Fear book recommended on this site. I'm on page 107.
Basically, I made this program that calculates factorials (with some help from the answers on the CD I admit). It's below.
In the get_factorials function, I've added in a second variable, int b, so that I can set this after I have printed out "Factorials = ". If I don't do this, get_factorials runs itself and outputs stuff prematurely (yeah I know I should probably have given b different names in main and get_factorials).
Is there a way of coding it so that it waits until you actually want it to run, without wasting code like int b etc.?
Thanks.
Code:#include <iostream> #include <math.h> using namespace std; // int b is only necessary below to stop it acting prematurely int get_factorials(int n, int b); int main() { int n, b; while(1) { cout << "Enter a number (0 to exit) and press ENTER: "; cin >> n; if (n == 0) break; cout << "Factorial(" << n << ") = "; b = 20; // This is just to stop the get factorials function running // and putting all the "n *" stuff out early. cout << get_factorials(n, b); cout << endl; } return 0; } int get_factorials(int n, int b) { if (n > 0) { cout << n; if (n > 1) cout << "*"; else cout << " = "; return n * get_factorials(n-1, b); } else return 1; }



LinkBack URL
About LinkBacks



CornedBee