Search Tutorials

Saturday, 20 April 2013

Convert a number into string in c

//This c code converts the given number into string
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<math.h>
int conv(long int);
char *str1[]={" ","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
char *str2[]={" ","ten","twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"};
char *str3[]={"hundred","thousand","lakh","crore"};
int main()
{
  char str[9];
  int a[9],n,m,r;
  int i,l;
  long int d=0;
  clrscr();

  printf("enter the string\n");
  gets(str);
  l=strlen(str);
 //for length // printf("%d\n",l);

  for(i=0;i<l;i++)
  {
  a[i]=str[i]-48;
  d=d+a[i]*pow(10,l-1-i);
  }
conv(d);
getch();
}

int  conv(long int n)
 {
 long int nn;
 nn=n;
 n=n/10000000;
 if(n!=0)
 {

    if(n>19)
    {
    printf("%s %s ",str2[n/10],str1[n%10]);
    }
    else
    {
    printf("%s ",str1[n]);
    }
 printf("%s ",str3[3]);
 }
 n=nn;
 n=(n/100000)%100;
 if(n!=0)
 {

    if(n>19)
    {
    printf("%s %s ",str2[n/10],str1[n%10]);
    }
    else
    {
    printf( "%s ",str1[n]);
    }
 printf("%s ",str3[2]);
 }
 n=nn;
  n=(n/1000)%100;
 if(n!=0)
 {

    if(n>19)
    {
    printf("%s %s ",str2[n/10],str1[n%10]);
    }
    else
    {
    printf(" %s",str1[n]);
    }
 printf("%s ",str3[1]);
 }
 n=nn;
  n=(n/100)%10;
 if(n!=0)
 {
 printf( "%s ",str1[n]);
 printf("%s ",str3[0]);
 }
 n=nn;
 n=n%100;
 if(n!=0)
 {

    if(n>19)
    {
    printf("%s %s ",str2[n/10],str1[n%10]);
    }
    else
    {
    printf( "%s",str1[n]);
    }

 }
 if(nn==0)
 {
 printf("zero");
 }

 }


1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete

Back to Top