// // Example 4.13 // Program to print a one- or two-digit positive integer in words // #include using namespace std; int main() { void printNumber(int n); // prototype int n; // one- or two-digit positive integer cout << "Enter a positive integer less than 100: "; cin >> n; if ((n < 1) || (n > 99)) cout << "Sorry, your number is out of range."; else printNumber(n); cout << endl; return 0; } // // Function to print a positive integer in words // Pre: n is an integer satisfying 0 < n < 100. // Post: n has been printed in words. // void printNumber(int n) { void printUnits(int unitsDigit); // prototypes void printTens(int tensDigit); void printTeens(int unitsDigit); int unitsDigit; // units digit int tensDigit; // tens digit unitsDigit = n % 10; tensDigit = n / 10; if (tensDigit == 0) printUnits(unitsDigit); else if (tensDigit == 1) printTeens(unitsDigit); else { printTens(tensDigit); if (unitsDigit > 0) { cout << "-"; printUnits(unitsDigit); } } } // // Function to print a word for the units digit // Pre: unitsDigit is an integer with 0 < unitsDigit < 10. // Post: unitsDigit has been printed in a word. // void printUnits(int unitsDigit) { switch (unitsDigit) { case 1: cout << "one"; break; case 2: cout << "two"; break; case 3: cout << "three"; break; case 4: cout << "four"; break; case 5: cout << "five"; break; case 6: cout << "six"; break; case 7: cout << "seven"; break; case 8: cout << "eight"; break; case 9: cout << "nine"; } } // // Function to print a word for the tens digit // Pre: tensDigit is an integer with 1 < tensDigit < 10. // Post: tensDigit has been printed in a word. // void printTens(int tensDigit) { switch (tensDigit) { case 2: cout << "twenty"; break; case 3: cout << "thirty"; break; case 4: cout << "forty"; break; case 5: cout << "fifty"; break; case 6: cout << "sixty"; break; case 7: cout << "seventy"; break; case 8: cout << "eighty"; break; case 9: cout << "ninety"; } } // // Function to print a number in the teens using words // Pre: unitsDigit is an integer with 0 <= unitsDigit < 10. // Post: Corresponding item has been printed in a word. // void printTeens(int unitsDigit) { switch (unitsDigit) { case 0: cout << "ten"; break; case 1: cout << "eleven"; break; case 2: cout << "twelve"; break; case 3: cout << "thirteen"; break; case 4: cout << "fourteen"; break; case 5: cout << "fifteen"; break; case 6: cout << "sixteen"; break; case 7: cout << "seventeen"; break; case 8: cout << "eighteen"; break; case 9: cout << "nineteen"; } }