Skip to content

Instantly share code, notes, and snippets.

@mtardy mtardy/K&R Exercise 4-12.c Secret
Last active Oct 30, 2015

Embed
What would you like to do?
#include <stdio.h>
#define MAX 100
void itoa (char s[], int n, int lim)
{
static int i = 0;
if (n < 0) {
s[i++] = '-';
lim++;
n = -n;
}
if (n / 10) {
itoa (s, n / 10, lim);
}
if (i < (lim - 1)) {
s[i++] = n % 10 + '0';
}
else {
s[i] = n % 10 + '0';
i = 0;
s[lim+1] = '\0';
}
}
int numberofdigits (n)
{
int i=0;
if (n < 0) {
n = -n;
}
while (n != 0) {
n = n / 10;
i++;
}
return i;
}
int main ()
{
int number = -123456789;
char string1[MAX] = { 0 };
char string2[MAX] = { 0 };
itoa(string1, number, numberofdigits(number));
printf("The string 1 is : %s\n", string1);
number = 987654321;
itoa(string2, number, numberofdigits(number));
printf("The string 2 is : %s\n", string2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.