unique, ad-free, freemium downloads

23 January 2018

A Program to Convert an N-Digit number to Words or Digits (explained)

converting numbers to digits or words
Using arrays and modulus operator, a number can be converted into its digits; afterwards it can be written in reverse order or in digits, or in Words, as this post indicates.
First, the number is broken into parts, the last digit gets stored in the array at first, the process continues, until all of the digits are stored in the individual array elements. Once this is achieved, we initiate printing process which uses a multiple selection (switch case) statement that prints the word respective to the digit. See the code below for further clarification.
#include <stdio.h>
#include <stdlib.h>
#define LIMIT 150

int main()
{
    int digits,number;
    int components[LIMIT];
    printf("\n\t\t *** DIGIT 2 WORD CONVERSION *** \n\n\n");

    do { //Error Control
        printf("\tPlease Enter number of Digits your number has : ");
        scanf("%d",&digits);
    } while (digits<0 && digits >=LIMIT);

    // Assuming that the user inputs correct number of digits
        printf("\tPlease Enter your number : ");
        scanf("%d",&number);

    // Seperating and Storing in an Array
    for (int i=1; i<=digits; i++){
        components[digits-i] = number%10;
        number /= 10;
    }

    printf("\n\n\t\t ** WORD NOTATION ** \n\n\t");
    for (int i=0; i<digits; i++){
        switch(components[i]){
        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;
        default:
            printf(" ");
        }
    }
    printf("\n\n");
}

An instance of this program executed in Windows using Code::Blocks is shown below. convertnumberstowords

No comments:

Post a Comment