blob: fc84e149a8b0e5474aa898d583fd40d069900904 (
plain) (
blame)
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
|
// 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
}
}
|