So Here I am trying to write a code, that converts a numerical number to its spelling format. For example, the user inputs any number like 320, then the output should be "Three Two Zero". Following is what I Have tried-
#include <stdio.h>
void main(){
long int num,rev=0 ;
printf("Enter any number to print in words: ");
scanf("%ld",&num);
while(num!=0){
rev=(rev*10)+(num%10);
num/=10 ;
}
while(rev!=0){
long int x=rev%10;
switch(x){
case 0:
printf("Zero ");
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;
}
}
}
Now the problem is that, this code is producing an infinite loop, like I input a number say 21, then it starts printing "Two Two Two Two........." till infinity.
Please Help me in resolving this question.
You need something that will make "rev!=0" true, which is rev = rev / 10 after the end of the switch. But creating an array and assigning zero, one, two, etc. and calling them using index could be better, I think you can think about this.
#include <stdio.h>
void main(){
long int num,rev=0 ;
printf("Enter any number to print in words: ");
scanf("%ld",&num);
while(num!=0){
rev=(rev*10)+(num%10);
num/=10 ;
}
while(rev!=0){
long int x=rev%10;
switch(x){
case 0:
printf("Zero ");
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;
}
rev = rev / 10;
}
}
And this is array approach:
#include <stdio.h>
void main(){
long int num,rev=0 ;
printf("Enter any number to print in words: ");
num = 123456789;
const char arr[10][6]= {
"Zero", "One", "two", "three", "four", "five", "six", "seven", "eight", "nine"
};
while(num!=0){
rev=(rev*10)+(num%10);
num/=10 ;
}
while(rev!=0){
long int x=rev%10;
printf("%s ", arr[x]);
rev = rev / 10;
}
}