Statement:
Write a program to convert given number to words. For example, if 2546 is input then output should be Two Five Four Six.
Required Knowledge:
Basic C programming, Switch Case, While loop
Logic to solve the problem:
Below is the step by step representation of the solution.
- Input the number from the user and store it in any variable of your choice, I'll use n here.
- Find the reverse of the given number and store it in any variable, say rev.
- Compute rev%10 and use the result in Switch Case to print required word of the number, i.e. construct 10 cases for 0,1,2,3,4,5,6,7,8,9 and print corresponding word.
- Remove the last digit of rev by using rev=rev/10.
- Repeat step 3,4 until rev is reduced to 0.
- In this case we'll have to find number of digits in both, original number and reversed number.
- Then we'll find the difference between number of digits in these two numbers. This difference will give us number of zeros which are present in the end of the number.
- Then we'll construct a loop which will print Zero number of zeros times in the end.
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | #include<stdio.h> int main () { int n, temp, rev = 0, nod = 0; int nod_original = 0, nod_rev = 0, noz_inlast = 0; printf ("Enter any number: "); scanf ("%d", &n); // No. of digits in original number. temp = n; //We need to store original in temp because in below loop value of rev can be alter while (temp != 0) { nod_original++; temp = temp / 10; } // finding reverse of number. while (n != 0) { rev = rev * 10 + n % 10; n = n / 10; } //No. of digits in reversed number. temp = rev; //We need to store reverse in temp because in below loop value of rev can be alter while (temp != 0) { nod_rev++; temp = temp / 10; } // Finding number of zeros in last. noz_inlast = nod_original - nod_rev; while (rev != 0) { switch (rev % 10) { case 0: printf ("Zero "); rev = rev / 10; break; case 1: printf ("One "); rev = rev / 10; break; case 2: printf ("Two "); rev = rev / 10; break; case 3: printf ("Three "); rev = rev / 10; break; case 4: printf ("Four "); rev = rev / 10; break; case 5: printf ("Five "); rev = rev / 10; break; case 6: printf ("Six "); rev = rev / 10; break; case 7: printf ("seven "); rev = rev / 10; break; case 8: printf ("Eight "); rev = rev / 10; break; case 9: printf ("Nine "); rev = rev / 10; break; default: break; } } // Printing zero number of zeros times for (int i = 0; i < noz_inlast; i++) { printf ("Zero "); } printf ("\n"); return 0; } |