Hi I don’t know why my code doesn’t show the result that I expected. The exercise was print out the spelling of a 2-digit number using function and if-else statement in C. When I ran the code it return nothing. ( This is a beginner exercise, so I can only think of this so sorry :(( ) Can you please check where I was wrong thank you very much!
#include <stdio.h>
// Consider the second number in that 2-digit number when the first number is 1
void ten(char b)
{
switch (b) {
case(0): printf("ten"); break;
case(1): printf("eleven"); break;
case(2): printf("twelve"); break;
case(3): printf("thirteen"); break;
case(4): printf("fourteen"); break;
case(5): printf("fifthteen"); break;
case(6): printf("sixteen"); break;
case(7): printf("seventeen"); break;
case(8): printf("eighteen"); break;
case(9): printf("nineteen"); break;
}
}
// Consider the second number in that 2-digit number when the first number is not 1
void morethanten(char b)
{
switch (b) {
case(0): break;
case(1): printf("one"); break;
case(2): printf("two"); break;
case(3): printf("three"); break;
case(4): printf("four"); break;
case(5): printf("five"); break;
case(6): printf("six"); break;
case(7): printf("seven"); break;
case(8): printf("eight"); break;
case(9): printf("nine"); break;
}
}
int main()
{
char a, b;
printf("Enter your 2-digit number: ");
scanf("%c%c", &a, &b);
// Consider the first number in that 2-digit number
switch (a) {
case(0): printf("That is not a 2-digit number"); break;
case(1): ten(b); break;
case(2): printf("Twenty"); morethanten(b); break;
case(3): printf("Thirty"); morethanten(b); break;
case(4): printf("Fourty"); morethanten(b); break;
case(5): printf("Fifthty"); morethanten(b); break;
case(6): printf("Sixty"); morethanten(b); break;
case(7): printf("Seventy"); morethanten(b); break;
case(8): printf("Eighty"); morethanten(b); break;
case(9): printf("Ninety"); morethanten(b); break;
}
return 0;
}
>Solution :
In your case statements, you are performing a check on an integer value and not the character representation of the digit.
case(1): ten(b); break;
Your case comparison for that particular statement would be:
case('1'): ten(b); break;
Here was a quick test after correcting the case comparisons, making the test against a character.
craig@Vera:~/C_Programs/Console/Spelling/bin/Release$ ./Spelling
Enter your 2-digit number: 12
twelve
Give that a try. Also, you may want to reference some tutorial literature to get a better understanding on testing within the switch block.