I was tasked to create a program that will ask for an integer input and will convert the inputted integer into its corresponding word format in English using if-else statements. Now, I have to modify it by using switch instead. Here is my progress so far.
#include<stdio.h>
#include<conio.h>
main()
{
int num,thousands,hundreds,tens,ones;
printf("Enter number (1-9999): ");
scanf("%d",&num);
if (num < 1 || num > 9999)
printf("Invalid number.");
else
{
thousands = num / 1000;
hundreds = num % 1000 / 100;
tens = num % 1000 % 100 / 10;
ones = num % 1000 % 100 % 10;
switch(thousands) {
case 1: printf("one thousand"); break;
case 2: printf("two thousand"); break;
case 3: printf("three thousand"); break;
case 4: printf("four thousand"); break;
case 5: printf("five thousand"); break;
case 6: printf("six thousand"); break;
case 7: printf("seven thousand"); break;
case 8: printf("eight thousand"); break;
case 9: printf("nine thousand"); break;
}
switch(hundreds) {
case 0: break;
case 1: printf(" one hundred"); break;
case 2: printf(" two hundred"); break;
case 3: printf(" three hundred"); break;
case 4: printf(" four hundred"); break;
case 5: printf(" five hundred"); break;
case 6: printf(" six hundred"); break;
case 7: printf(" seven hundred"); break;
case 8: printf(" eight hundred"); break;
case 9: printf(" nine hundred"); break;
}
switch(tens) {
{
case 1:
{
switch(ones) {
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(" fifteen"); break;
case 6: printf(" sixteen"); break;
case 7: printf(" seventeen"); break;
case 8: printf(" eighteen"); break;
case 9: printf(" nineteen"); break;
}
break;
}
break;
}
case 2: printf(" twenty"); break;
case 3: printf(" thirty"); break;
case 4: printf(" forty"); break;
case 5: printf(" fifty"); break;
case 6: printf(" sixty"); break;
case 7: printf(" seventy"); break;
case 8: printf(" eighty"); break;
case 9: printf(" ninety"); break;
}
if (tens != 1)
{
switch(ones) {
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;
}
}
}
getch();
}
It works fine but is it possible to make that one if statement (if (tens != 1)) into a switch statement instead? Would really appreciate any feedback, thanks!