Exercise 4-12 (Recursive itoa - Integer to string)

Chapter_4     Exercise_4-11     Quick_sort Exercise_4-13







Exercise 4-12     K&R, p. 88


Exercise 4-12. Adapt the ideas of ch4-printd to write a recursive version of itoa (Exercise_3-4); that is, convert an integer into a string by calling a recursive routine.




itoar.c         download


#include <stdio.h> // for printf(), scanf()

#define SIZE 100 // array size (no of digits)
// recursive itoa():
int itoa(int , char []); // int to string (char array), return length

int main()
{
int i, n;
char array[SIZE];

printf("Type an integer, [+-]?[0-9]+\n");
scanf("%d", &n);

if (n < 0) {array[0] = '-';}
i = itoa(n, array);
array[i] = '\0';

printf("%s\n", array);

return 0;
}

// int n to string (char array), recursive itoa():
int itoa(int n, char s[]) // start writing at position pos in array s[]
{ // return last position written (length of s[])
int sign = 1;
int pos = 0; // position

if (n < 0)
{
sign = -1;
pos = 1;
}

if (n / 10) // if (n / 10 != 0)
{pos = itoa(n / 10, s);} // recursive call

s[pos++] = (n % 10) * sign + '0';

return pos;
}
/*
gcc itoar.c -o itoar
./itoar
Type an integer, [+-]?[0-9]+
0
0

./itoar
Type an integer, [+-]?[0-9]+
+0
0

./itoar
Type an integer, [+-]?[0-9]+
-0
0

./itoar
Type an integer, [+-]?[0-9]+
123
123

./itoar
Type an integer, [+-]?[0-9]+
+123
123

./itoar
Type an integer, [+-]?[0-9]+
-123
-123

./itoar
Type an integer, [+-]?[0-9]+
-2147483648 // INT_MIN // limits.h
-2147483648

./itoar
Type an integer, [+-]?[0-9]+
-2147483649 // INT_MIN-1 (underflow)
2147483647 // INT_MAX

./itoar
Type an integer, [+-]?[0-9]+
2147483647 // INT_MAX
2147483647

./itoar
Type an integer, [+-]?[0-9]+
2147483648 // INT_MAX+1 (overflow)
-2147483648 // INT_MIN
*/









Chapter_4     Exercise_4-11     Quick_sort BACK_TO_TOP Exercise_4-13



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo