Advertisement
Masovski

[Conditional-Statements] 11. Numbers As Words

Mar 26th, 2014
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.05 KB | None | 0 0
  1. using System;
  2.  
  3. class NumberAsWords
  4. {
  5.     static void Main()
  6.     {
  7.         Console.Write("Please enter a number (0-999): ");
  8.         int number = int.Parse(Console.ReadLine());
  9.  
  10.         string[] unitsMap = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve",
  11.                             "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
  12.         string[] tensMap = { "Zero", "Ten", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
  13.         string words = null;
  14.  
  15.         int hundreds = number / 100;
  16.         int tens = number / 10 % 10;
  17.         int units = number % 10;
  18.  
  19.         bool isZero = hundreds == 0 && tens == 0 && units == 0;
  20.  
  21.         if (number < 0 || number > 999)
  22.         {
  23.             Console.WriteLine("Invalid number. Enter a number from 0 to 999.");
  24.         }
  25.         else
  26.         {
  27.             if (isZero)
  28.             {
  29.                 words += unitsMap[units];
  30.             }
  31.             if (hundreds != 0 && tens >= 0 && units != 0)
  32.             {
  33.                 words += unitsMap[hundreds] + " hundred and ";
  34.             }
  35.             else if (hundreds != 0 && tens >= 0 && units == 0)
  36.             {
  37.                 words += unitsMap[hundreds] + " hundred and ";
  38.             }
  39.             else if (hundreds != 0 && tens == 0)
  40.             {
  41.                 words += unitsMap[hundreds] + " hundred ";
  42.             }
  43.             if (tens != 0)
  44.             {
  45.                 if (tens == 1)
  46.                 {
  47.                     words += unitsMap[units + 10] + " ";
  48.                 }
  49.                 else
  50.                 {
  51.                     words += tensMap[tens] + " ";
  52.                     if (units != 0)
  53.                     {
  54.                         words += unitsMap[units];
  55.                     }
  56.                 }
  57.             }
  58.             if (units != 0 && tens == 0)
  59.             {
  60.                 words += unitsMap[units];
  61.             }
  62.             Console.WriteLine(words);
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement