Spread the love
How can I convert numbers to strings (itoa() function)?
The C library function char * itoa ( int value) converts the integer argument to string. This problem is about to write own itoa( ) function which has same argument parameter and return type. Following has a simplest logic to do so:
Algorithm
Algorithm is pretty simple, we divide number, collect remainder and convert it from integer value to ASCII by adding 48(ASCII value of zero) to integer value until number becomes zero.
#include <stdio.h> char* ItoA(int x) { int remainder; char Num_str[33]; Num_str[32]='\0'; char *ptr = &Num_str[32]; do { remainder = x % 10; x /= 10; *--ptr = (unsigned char)remainder + 48; // Add zero(0 = 48<ASCII>) to convert in proper ASCII value }while(x!=0); return (ptr); } int main() { int i=12345; printf("%s", ItoA(i) ); return 0; }
Suggested Reading
- Write your own C program to implement the atoi() function
- Write a C program to reverse the string without using strrev() ?
- Convert decimal number into hexadecimal octal binary – single universal logic