// As we were discussing chapter 6 and subprograms as process abstractions, // I used a procedure that prints n copies of a character as an example. // We all know how to write that code, so we could discuss the underlying // concepts concerning it. But I also reminded the students that the code // could be written recursively (we needed to discuss activation records). // SO .... // This program prints whatever single non-whitespace character that is // entered as the first input as many times as the integer value provided // as the second input unless that second input is less than zero or not // an integer. If it is a neagtive integer, it will use the absolute value. // If it isn't an integer, it will use 42. // The program will do this printing twice; once iteratively and then once // recursively. // // Note that I didn't write this in one big program or even all at once. // I know that the functions will work, so I'm writing the input and error // recovery first. I wrote the comments and function prototypes before that. // // Beth Katz, October 2003 #include using namespace std; // print sym n times - iterative version void printSymN_iterative(char sym, int n); // print sym n times - recursive version void printSymN_recursive(char sym, int n); int main( ) { char ch; int times; cout << "Please enter a character and the number of times to print it: "; cin >> ch; cin >> times; if (!cin) { times = 42; } else if (times < 0) { times = - times; } cout << "Iteratively:" << endl; printSymN_iterative(ch, times); cout << "Recursively:" << endl; printSymN_recursive(ch, times); return 0; } // print sym n times - iterative version void printSymN_iterative(char sym, int n) { for (int i = 1; i <= n; i++) { cout << sym; } cout << endl; } // print sym n times - recursive version void printSymN_recursive(char sym, int n) { if (n <= 0) { cout << endl; } else { cout << sym; printSymN_recursive(sym, n-1); } }