# Thread: itoa function : doesn't work for -ve number ?????

1. ## itoa function : doesn't work for -ve number ?????

Hi !

This is a function itoa(int n , char s[]) which converts an integer to a string. I have tried to implement it recursively. The program works fine except one problem:

IT DOESN"T WORK FOR -ve NUMBERS ??? WHY ????????
I DON"T UNDERSTAND ???? CAN ANY ONE HELP ME ON THIS !!!

The code is as follows :

Code:
```#include<stdio.h>
#include<string.h>

/* *********************************************************************************** */
/* This program defines a recursive function itoa() which converts integer to a string
/* *********************************************************************************** */

static int i = 0;           /* variables to keep track of the index of the string */
static int sign = 1;        /* variable to keep track of the sign of the integer */

void reverse(char s[]);    /* function declaration : function to reverse a string */

void itoa(int n, char s[])
{
if(i == 0)             /* make the number positive if it is negative */
if (sign < 0)
{
n = -n;
sign *= -1;
}

/* store each digit in the string ( in reverse order )*/

if(n)
{
s[i++] = n%10 + '0';
itoa(n/10, s);
}

else
{
if (sign < 0)                 /* if the number was negative place a -ve sign at the end */
{
s[i++] = '-';
s[i] = '\0';
reverse(s);
return;         /* place a NULL character to mark the end of the string */
}

else
{
s[i] = '\0';
reverse(s);
return;
}
}
}

void reverse(char s[])
{
int i, j, temp;         /* local variable to reverse the string */
for( i = 0, j = (strlen(s) - 1); i < j; i++, j--)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}

int main()
{
char s[]= "";
int n = -10;
itoa(n, s);
printf("%s\n", s);

return 0;
}```

2. Hi !

I figured my stupid mistake out !!!!
Sorry for the trouble
I made the most stupid mistake "check if the number is negative not sign " !!!!!!!!
man I must have been on something when i was doing this !!!!

Sorry again

3. hello, look at this line
Code:
`static int sign = 1;`
which should me something like this right
[code
static int sign = -1;
[/code]

try out now, is any problem let me know

s.s.harish