Program opened below. You can scroll through the algorithm, Java code and output.
Program 02
Number Below 1000 in Words
Question
Accept a natural number from 1 to 999 and print it in English words. Print Out of Range for any other value.
Algorithm
Step 1: Begin execution and create a Scanner.
Step 2: Read the input number n.
Step 3: Test whether n is between 1 and 999.
Step 4: Print Out of Range and stop for invalid input.
Step 5: Prepare an array containing words from one through nineteen.
Step 6: Prepare another array of multiples of ten from twenty through ninety.
Step 7: Initialize an empty result string.
Step 8: Check whether the number contains hundreds.
Step 9: If it does, obtain its hundreds digit.
Step 10: Append the hundreds word followed by Hundred.
Step 11: Remove the hundreds portion using remainder 100.
Step 12: Append and when a nonzero remainder remains.
Step 13: If the remainder is at least twenty, append its tens word.
Step 14: Append the remaining units word when required.
Step 15: For a remainder below twenty, append the corresponding direct word.
Step 16: Display the completed words and stop.
Java program
Javaimport java.util.*;
class NumberWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n < 1 || n > 999) {
System.out.println("Out of Range");
return;
}
String[] ones = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
String[] tens = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
String result = "";
if (n >= 100) {
result = ones[n / 100] + " Hundred";
n %= 100;
if (n > 0) {
result += " and ";
}
}
if (n >= 20) {
result += tens[n / 10];
n %= 10;
if (n > 0) {
result += " " + ones[n];
}
} else {
result += ones[n];
}
System.out.println(result);
}
}Sample output
Input: 201
Output: Two Hundred and One