exc/k&r/03-control-flow/03-04.c

52 lines
944 B
C

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <limits.h>
void itoa(int n, char s[]);
/* passes arg to itoa or INT_MIN if no arg is given */
int main(int argc, char *argv[])
{
int n;
if (argc < 2) {
printf("expected : %d\n", INT_MIN);
n = INT_MIN;
} else
n = atoi(argv[1]);
char s[(int)log10(INT_MAX) + 3];
itoa(n, s);
printf("%s\n", s);
return 0;
}
void reverse(char *s);
/* itoa: convert n to characters in s */
void itoa(int n, char s[])
{
int i;
unsigned absn = (n < 0) ? -n : n; /* handles INT_MIN */
i = 0;
do {
s[i++] = absn % 10 + '0';
} while ((absn /= 10) > 0);
if (n < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
/* reverse: reverses string s in place */
void reverse(char *s)
{
char c, *s2;
for (s2 = s + strlen(s) - 1; s < s2; s++, s2--)
c = *s, *s = *s2, *s2 = c;
}