From ca34f80cacd236c8089e05d9f1fcc7958da3e500 Mon Sep 17 00:00:00 2001 From: Sadeep Madurange Date: Sat, 4 Dec 2021 13:31:01 +0800 Subject: 3.6 --- 3/6.c | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 3/6.c diff --git a/3/6.c b/3/6.c new file mode 100644 index 0000000..bb3636f --- /dev/null +++ b/3/6.c @@ -0,0 +1,66 @@ +#include +#include +#include + +#define MAXLEN 1000 + +/* converts n to s with width w */ +void itoa(int n, char s[], int w); + +int main(int argc, char *argv[]) { + int i, c, n, w; + char s[MAXLEN]; + + printf("Number to convert to string: "); + for (i = 0; i < MAXLEN - 1 && (c = getchar()) != '\n' && c != EOF; i++) + s[i] = c; + s[i] = 0; + n = atoi(s); + + printf("Width: "); + for (i = 0; i < MAXLEN - 1 && (c = getchar()) != '\n' && c != EOF; i++) + s[i] = c; + s[i] = 0; + w = atoi(s); + + itoa(n, s, w); + printf("%d as string of width %d: %s\n", n, w, s); + + return 0; +} + +void reverse(char s[]) { + int c, i, j; + + for (i = 0, j = strlen(s) - 1; i < j; i++, j--) { + c = s[i]; + s[i] = s[j]; + s[j] = c; + } +} + +void itoa(int n, char s[], int w) { + int i; + + i = 0; + + if (n >= 0) { + do { + s[i++] = n % 10 + '0'; + } while ((n /= 10) > 0); + } else { + do { + s[i++] = -(n % 10) + '0'; + } while ((n /= 10) <= -1); + } + + if (n < 0) + s[i++] = '-'; + + while (i < MAXLEN - 1 && i < w) + s[i++] = ' '; + + s[i] = 0; + + reverse(s); +} \ No newline at end of file -- cgit v1.2.3