1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include <iostream>
#include <iomanip>
#include <algorithm> // for min, max
using namespace std;
// ===========1 TO n==================
void show_1_to_n_loop(int n) { // 1 to n, looping, PROVIDED, DO NOT CHANGE
for (int i=1; i<=n; ++i) cout<<i<<" ";
}
// Constraints: No loops allowed; no static local or global variables.
void show_1_to_n_recurse(int n) { // 1 to n, recursive
if (n<=0) // won't recurse any further once n gets to 0, no negative numbers
{
cout <<"";
}
else{
show_1_to_n_recurse(n-1);
cout <<n<<" ";
}
}
// ===========n TO 1==================
void show_n_to_1_loop(int n) { // looping, PROVIDED, DO NOT CHANGE
for (int i=n; i>=1; --i) cout<<i<<" ";
}
// Constraints: No loops allowed; no static local or global variables.
void show_n_to_1_recurse(int n) { // recursive
if (n>=0)
{
cout <<"";
}
else{
cout <<n<<" ";
show_n_to_1_recurse(n+1);
}
}
// ===========MESSAGE LAYOUT==================
enum control_flow_t {functional, looping, recursive};
void show_test(int n, string s, control_flow_t control_flow) {
// utility function to format test output
// n: test number; s: "description"; control_flow: functional, looping or recursive
static const string fx="functional", sl="looping", sr="recursive";
int max_len=max(fx.size(), max(sl.size(), sr.size()));
string msg;
switch (control_flow) {
case functional: msg=fx; break;
case looping: msg=sl; break;
case recursive: msg=sr; break;
default: msg="??"; break;
}
char iorr=msg[0];
msg=" ("+msg+"): ";
cout<<"\n"<<n<<iorr<<") "<<s<<setw(max_len+5)<<left<<msg;
}
int main () {
cout<<"start...\n";
show_test(1, "show_1_to_n", looping); show_1_to_n_loop(15);
show_test(1, "show_1_to_n", looping); show_1_to_n_loop(-9); // handle unexpected values
show_test(1, "show_1_to_n", recursive); show_1_to_n_recurse(15);
show_test(1, "show_1_to_n", recursive); show_1_to_n_recurse(-9); // avoid runaway recursion
cout<<endl;
show_test(2, "show_n_to_1", looping); show_n_to_1_loop(11);
show_test(2, "show_n_to_1", looping); show_n_to_1_loop(-5); // handle unexpected values
show_test(2, "show_n_to_1", recursive); show_n_to_1_recurse(11);
show_test(2, "show_n_to_1", recursive); show_n_to_1_recurse(-5); // avoid runaway recursion
cout<<endl;
cout<<"\n...end\n";
return 0;
} // end of main
|