This blog is under construction

Saturday 22 June 2013

C program to print digits of a number in words

Write a C program to convert each digits of a number into words.



  #include <stdio.h>
  int main() {
        int res = 0, ch, data, mod;
        printf("Enter your input:");
        scanf("%d", &data);

        /* reverse the given input first */
        while (data > 0) {
                mod = data % 10;
                res = (res * 10) + mod;
                data = data / 10;
        }
        data = res;

        /* print the digits from LSB to MSB */
        while (data > 0) {
                ch = data % 10;
                switch (ch) {
                        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;
                }
                data = data / 10;
        }
        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/cpgms/lab_pgms/02_control_flow$ ./a.out
  Enter your input: 981234
  nine eight one two three four 



No comments:

Post a Comment