Using Switch or If Else Structure

closed account (EwkNwA7f)
If the user input 1 to 999.
The output is in number in words.
for example

Number:45
NUmber in Words:FortyFive


Can you help me about the code for this program.
Im having a trouble.

Thankyou
Try to understand the two stages of the program and write another version.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <string>

using namespace std;

int main()
{	
	int n;
	cout << "Enter an integer between 1 and 999: ";
	cin >> n;
	if(n < 1 || n > 999) return 0;
	string words;
	string hund = "Hundred";
	string str1[9] = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
	string str2[9] = {"Eleven", "Twelf", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
	string str3[9] = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninenty"};
	
	int part = n % 100;
	int h = n / 100;     // h = hundreds digit
	int t = part / 10;   // t = tens digit
	int u = part % 10;   // u = units digit
	cout << "\nNumber in words: ";
	
	if(h == 0)
	{
		if(t == 0) words = str1[u - 1]; 
		
		if(t > 0 && u == 0) words = str3[t - 1]; 
		
		if(t == 1 && u > 0) words = str2[u - 1]; 
		
		if(t > 1 && u > 0) words = str3[t - 1] + str1[u - 1]; 
	}
	
	if(h > 0)
	{
		if(t == 0 && u == 0) words = str1[h - 1] + hund;
		
		if(t == 0 && u > 0) words = str1[h - 1] + hund + str1[u - 1];
		
		if(t > 0 && u == 0) words = str1[h - 1] + hund + str3[t - 1];
		
		if(t == 1 && u > 0) words = str1[h - 1] + hund + str2[u - 1];
		
		if(t > 1 && u > 0) words = str1[h - 1] + hund + str3[t - 1] + str1[u - 1];
	}
	
	cout << words << "\n\n";
	return 0;
}

Hope helps.
Last edited on
closed account (EwkNwA7f)
thankyou.
You're welcome!
Topic archived. No new replies allowed.