C Programming Examples Tutorial Index

C String Programs

This program is used to convert a given number into its / their equivalent words.



Program:

#include<stdio.h>
void main()
{
  int num, i=0, x, d;
  char * word_no [2000];
  printf ("Enter an integer value: \n");
  scanf ("%d", &num);
  while (num)
  {
    d = num %10;
    num = num /10;
    switch(d)
    {
      case 0: word_no[i++] = "zero";
      break;
      case 1: word_no[i++] = "one"; 
      break;
      case 2: word_no[i++] = "two"; 
      break;
      case 3: word_no[i++] = "three"; 
      break;
      case 4: word_no [i++] = "four"; 
      break;
      case 5: word_no [i++] = "five"; 
      break;
      case 6: word_no [i++] = "six"; 
      break;
      case 7: word_no [i++] = "seven"; 
      break;
      case 8: word_no [i++] = "eight"; 
      break;
      case 9: word_no[i++] = "nine"; 
      break;
    }
  }
  for(x=i-1; x>=0; x--){
  printf ("%s ",word_no[x]);
  }
}

Explanation:

First of all, you have to include the stdio header file using the "include" preceding # which tells that the header file needs to be process before compilation, hence named preprocessor directive.

Then you have to define the main() function and it has been declared as void since no return type is associated with it. The inside the main() function, four integer type variables name 'num', 'i', 'x', d' are declared and i is initialized with the value 0. Then another array name 'word_no[]' is declared having the type character (Character array). Then the printf() is used display a message - ("Enter an integer value: \n", where \n is an escape sequence that is used to give a new line in the output stream.

The statement scanf ("%d", &num); is used to take input from the user and store it into the variable num. Then a while loop is implemented which tells that if num is not equaled to 0 then the statement will be true and it will go inside the loop and perform the execution.
Within the while loop there is a statement:

d = num %10; where the modulus of variable num is done with 10 and gets stored in 'd'. Then the statement - num = num /10; means the calculated value of num divided by 10 gets stored back to num. Then you have to use the switch-case statement where all the cases for all the digits are defined with respect to their words in all of their switch cases starting from 0 till 9.
Finally, a for loop is used which iterate to print the array values of word_no[] array. Inside for loop, the x is used to count the value from value 'i-1' till 0, decrementing the value of x.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram