diff options
| author | Fuwn <[email protected]> | 2024-04-07 23:18:32 -0700 |
|---|---|---|
| committer | Fuwn <[email protected]> | 2024-04-07 23:18:32 -0700 |
| commit | c1b6ffe70bd281c6c230fd63fabcaac2aff47514 (patch) | |
| tree | e8af3b1782a7cd0754590ed618fddc1bdb9b7385 /chapter9/vertical.cxx | |
| download | dscode-main.tar.xz dscode-main.zip | |
Diffstat (limited to 'chapter9/vertical.cxx')
| -rw-r--r-- | chapter9/vertical.cxx | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/chapter9/vertical.cxx b/chapter9/vertical.cxx new file mode 100644 index 0000000..fc84e14 --- /dev/null +++ b/chapter9/vertical.cxx @@ -0,0 +1,47 @@ +// FILE: vertical.cxx
+// two recursive functions that write the digits of a number vertically.
+#include <iostream> // Provides cin, cout
+#include <cstdlib> // Provides EXIT_SUCCESS
+using namespace std;
+
+void write_vertical(unsigned int number);
+void super_write_vertical(int number);
+
+int main( ) {
+ int i;
+
+ cout << "Please type a non-negative number: ";
+ cin >> i;
+ cout << "The digits of that number are:" << endl;
+ write_vertical(i);
+
+ cout << "Please type a negative number: ";
+ cin >> i;
+ cout << "The digits of that number are:" << endl;
+ super_write_vertical(i);
+
+ cout << "Let's get vertical!" << endl;
+ return EXIT_SUCCESS;
+}
+void write_vertical(unsigned int number) {
+ if (number < 10)
+ cout << number << endl; // Write the one digit
+ else {
+ write_vertical(number/10); // Write all but the last digit
+ cout << number % 10 << endl; // Write the last digit
+ }
+}
+void super_write_vertical(int number) {
+ if (number < 0) {
+ cout << '-' << endl; // print a negative sign
+ super_write_vertical(abs(number)); // abs computes absolute value
+ // This is Spot #1 referred to in the text.
+ }
+ else if (number < 10)
+ cout << number << endl; // Write the one digit
+ else {
+ super_write_vertical(number/10); // Write all but the last digit
+ // This is Spot #2 referred to in the text.
+ cout << number % 10 << endl; // Write the last digit
+ }
+}
|