ch3-Recursion (CatsInHats)
Chapter_3 Exercise_3-4 GoTo | Exercise_3-5 |
Note: In C/C++ and other Procedural_programming_languages, recursion should be used with care. See the discussion about Recursion_versus_iteration, Imperative_programming, and Functional_programming on Wikipedia. Check also recursion pros and cons online.
CatsInHats.cpp TCP1, p. 137 download
// Simple demonstration of recursion
#include <iostream>
using std::cout;
using std::endl;
void removeHat(char cat);
int main()
{
removeHat('A');
return 0;
}
void removeHat(char cat)
{
for(char c = 'A'; c < cat; c++)
{cout << " ";}
if(cat <= 'Z')
{
cout << "cat " << cat << endl;
removeHat(cat + 1); // Recursive call
}
else {cout << "VOOM!!!" << endl;} // end condition for recursion
}
/*
g++ CatsInHats.cpp -o CatsInHats
./CatsInHats
cat A
cat B
cat C
cat D
cat E
cat F
cat G
cat H
cat I
cat J
cat K
cat L
cat M
cat N
cat O
cat P
cat Q
cat R
cat S
cat T
cat U
cat V
cat W
cat X
cat Y
cat Z
VOOM!!!
*/
Chapter_3 Exercise_3-4 GoTo | BACK_TO_TOP | Exercise_3-5 |
Comments
Post a Comment