Need a project done?

C++ Programming Developer

Search This Blog

C++ program Integer to English conversion



Write a program that takes an integer and displays the English name of that value.

Examples:

10 -> ten
121 -> one hundred twenty one
1032 -> one thousand thirty two
11043 -> eleven thousand forty three
1200000 -> one million two hundred thousand

Solution:


#include <iostream>
using namespace std;

void sperate_digits(int [], int);
void speak(int);
void speak_digit(int);
int i = 0;

int main()
{
cout << "Number: "; int num; cin >> num;

//seperating digits.
int digit[10];
sperate_digits(digit, num);

for ( ; i>0; i--)
{
if (i == 1 || i == 3)
speak_digit(digit[i-1]);
else if (i==2)
speak(digit[i-1]);
else
if (i%2 == 0)//i is the number of digits of number entered by user
{
speak_digit(digit[i-1]);
}
else if(i%2 == 1)
speak(digit[i-1]);

if (i==3 || i%2 == 0) //odd.
switch(i)
{
case 3:
cout << " hundred";
break;
case 4:
case 5:
cout << " thousand";
break;

case 6:
case 7:
cout << " Lac";
break;
case 8:
case 9:
cout << "Arab";
break;
}
cout << ' '; //space.
}
return 0;
}

void sperate_digits(int digit[], int num)
{
for ( ; num != 0; i++)
{
digit[i] = num%10;
num /= 10;
}
}

void speak(int x)
{
switch(x)
{
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";
break;
}
cout << ' '; //space
}

void speak_digit(int x)
{
switch(x)
{
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";
break;
}
cout << ' '; //space.
}


Share knowledge: (link to this post is http://adf.ly/biZjY)

1 comment:

  1. The logic used is correct. But there is a bug. When you enter any number with 1 in middle (3-digit number) then incorrect output comes. For example when you type 111 then output comes to be "one hundred one" instead of "one hundred eleven" which is wrong. Rest all is correct :)

    ReplyDelete

"Don't let anyone ever make you feel like you don't deserve what you want."