Algorithm For Converting Number Into Words
Algorithm For Converting Number Into Words
1. Declaration
String astr
integer r,q,le,i=1
String[] n1 = {"one ","two ","three ","four ","five ","six
","seven ","eight ","nine ","ten ","eleven ","twelve ","thirteen
","fourteen ","fifteen ","sixteen ","seventeen ","eighteen
","nineteen ","twenty "};
String[] n2 = {"ten ","twenty ","thirty ","forty ","fifty ","sixty
","seventy ","eighty ","ninety "};
String[] n3 = {" ","hundred ","thousand ","lakhs ","crores
","arab "};
Store number into a variable q
Store the length of string in variable le and initialize astr to “”
2.Loop till q is greater than 0
Number is to be divided by 100 expect in second iteration
where it needs to be by 10 variable r will store remainder while
q quotient. In each iteration last two digits will be considered
if (i != 2) then r = q % 100 and q = q/100 otherwise r = q % 10
and q = q/10;
If number is less than or equal to 20 then corresponding word
with respect to reminder and iteration will be taken from n1
and n3 array
Else
Corresponding word with respect to quotient, remainder and
iteration will be from n2, n1 and n3 array
Increment the iteration
Go to step 2
3. Return the number
Java Program
import java.util.Scanner;
// @author Dr SP Kulshrestha
public class Number_to_word {
static String nword(int a)
{
String astr;
int r,q,le,i=1;
q = a;
String[] n1 = {" ","one ","two ","three ","four ","five ","six ","seven
","eight ","nine ","ten ","eleven ","twelve ","thrirteen ","fourteen ","fifteen
","sixteen ","seventeen ","eighteen ","nineteen ","twenty "};
String[] n2 = {" ","ten ","twenty ","thirty ","forty ","fifty ","sixty ","seventy
","eighty ","ninty "};
String[] n3 = {" ","hundred ","thousand ","lakhs ","crores ","arab "};
astr = "";
do
{
if (i != 2)
{
r = q % 100;
q = q/100;
} else
{
r = q % 10;
q = q/10;
}
if (r>0)
{
if (r <= 20 )
astr = n1[r]+n3[i-1] +astr;
else
{astr = n2[(r/10)]+ n1[(r %10)]+n3[i-1] +astr;}
}
i = i+1;
} while (q>0) ;
return astr;
}
public static void main(String[] args)
{
String abc ;
int numb1;
Scanner s = new Scanner(System.in);
System.out.println("Enter number which needs to convert in word: ");
numb1 = s.nextInt();
System.out.println("You entered: " + numb1);
abc = nword(numb1);
System.out.println(" Number in words : " + abc ); } }