Saturday, 18 November 2017

Programs on C - Convert int number to string and display

Without using any library functions (except scanf and printf), convert integer number as provided by user to a character string and display the string.

#include <stdio.h>

void tostring(char [], int);

int main()

{

char str[10]; //len is 10 considering max storage size of int

int num,result;

printf("Enter a number: ");

scanf("%d",&num);

tostring(str,num); //convert to string

printf("Number converted to string: %s\n",str);

return 0;

}

//function to convert to string

void tostring(char str[], int num)

{

int i, rem, len =0, n;

n=num;

while(n!=0)

{

len++; //get length for string/digits in int

n=n/10;

}

for(i=0;i<len;i++) //convert and store in string

{

rem=num%10; //last digit fetched first

num=num/10; //continue fetching rest of the digits

str[len-(i+1)]=rem + '0'; //start storing string with max-1 index first

}

str[len]='\0'; //null to end the string[max]

}

No comments:

Post a Comment