aboutsummaryrefslogtreecommitdiff
path: root/4.14.c
diff options
context:
space:
mode:
authorsinanmohd <pcmsinan@gmail.com>2022-06-15 18:04:45 +0530
committersinanmohd <pcmsinan@gmail.com>2022-06-16 00:51:08 +0530
commit8a492bf521e46c70d69fae79934940eef931bcde (patch)
treecc166f304193fbb0d8d037d9377006b682e47cbc /4.14.c
parentf4dcb9e585d331c6bccccd42daedda18222ef672 (diff)
finish off 4
Diffstat (limited to '4.14.c')
-rw-r--r--4.14.c57
1 files changed, 57 insertions, 0 deletions
diff --git a/4.14.c b/4.14.c
new file mode 100644
index 0000000..17a48a9
--- /dev/null
+++ b/4.14.c
@@ -0,0 +1,57 @@
+#include <stdio.h>
+#include <string.h>
+
+#define MAXLEN 15
+#define swap(array, i, j) int temp = array[i];\
+ array[i] = array[j]; \
+ array[j] = temp;
+
+void reverse(char str[], size_t left, size_t right);
+char* itoa(int n, char str[]);
+
+int
+main(void)
+{
+ int n = 42069;
+ char str[MAXLEN];
+
+ printf("%d\n", n);
+ printf("%s\n", itoa(n, str));
+
+ return 0;
+}
+
+void
+reverse(char str[], size_t left, size_t right)
+{
+ if (left >= right)
+ return;
+
+ swap(str, left, right);
+ reverse(str, left+1, right-1);
+}
+
+char*
+itoa(int n, char str[])
+{
+ int sign, i;
+
+ /* to include the most -ve int */
+ n = ((sign = n) < 0) ? -(n+1) : n-1;
+
+ i = 0;
+ do {
+ str[i++] = n%10 + '0';
+ } while ((n /= 10) > 0);
+
+ if (sign <0)
+ str[i++] = '-';
+
+ /* part of "to include the most -ve int" */
+ str[0] += 1;
+ str[i] = '\0';
+
+ reverse(str, 0, strlen(str)-1);
+
+ return str;
+}