From cafa6492665c3d5c21f0446914b24082d1fecd32 Mon Sep 17 00:00:00 2001 From: ayush <152896667+kkaname@users.noreply.github.com> Date: Sun, 7 Dec 2025 02:32:57 +0530 Subject: [PATCH 1/2] Simplify character input loop in loop.c since they have asked in the question to not to use the relational operators, I have written the code for the loop without the relational operators(&& and ||) --- chapter_2/exercise_2_02/loop.c | 39 +++++++++++++++------------------- 1 file changed, 17 insertions(+), 22 deletions(-) diff --git a/chapter_2/exercise_2_02/loop.c b/chapter_2/exercise_2_02/loop.c index 5cfbb05..9228c86 100644 --- a/chapter_2/exercise_2_02/loop.c +++ b/chapter_2/exercise_2_02/loop.c @@ -5,31 +5,26 @@ int main(void) { char s[MAXLINE]; - - // int i; - // int c; - // for (i = 0; (i < MAXLINE - 1) * ((c = getchar()) != '\n') * (c != EOF); ++i) - // { - // s[i] = c; - // } - - int i = 0; - int loop = 1; - while (loop) - { - char c = getchar(); - - if (i >= (MAXLINE - 1) || c == '\n' || c == EOF) - { - loop = 0; + int c, i = 0; + + while (1){ + if (i >= MAXLINE - 1) + break; + + c = getchar(); + + if (c == '\n') + break; + else if (c == EOF) + break; + else + s[i] = c; + + ++i; } - s[i++] = c; - } - - s[i] = '\0'; + printf("\n%s\n", s); - printf("%s", s); return 0; } From d37125c9e7c8464c206fc68ebe7f7023bcc359ab Mon Sep 17 00:00:00 2001 From: ayush <152896667+kkaname@users.noreply.github.com> Date: Sun, 7 Dec 2025 02:43:22 +0530 Subject: [PATCH 2/2] Fix character assignment and null termination in loop --- chapter_2/exercise_2_02/loop.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/chapter_2/exercise_2_02/loop.c b/chapter_2/exercise_2_02/loop.c index 9228c86..2b60f5b 100644 --- a/chapter_2/exercise_2_02/loop.c +++ b/chapter_2/exercise_2_02/loop.c @@ -18,12 +18,11 @@ int main(void) else if (c == EOF) break; else - s[i] = c; - - ++i; + s[i++] = c; } + s[i] = '\0'; - printf("\n%s\n", s); + printf("%s\n", s); return 0;