From c8cbf8ab44dea7b93177b736cc1a473ca9dffe89 Mon Sep 17 00:00:00 2001 From: Ayush Hegde Date: Wed, 10 Dec 2025 17:54:23 +0530 Subject: [PATCH 1/2] Implemented the solution by using while loop and without using any relational operators --- chapter_2/exercise_2_02/loop.c | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/chapter_2/exercise_2_02/loop.c b/chapter_2/exercise_2_02/loop.c index 5b127a6..ef9494c 100644 --- a/chapter_2/exercise_2_02/loop.c +++ b/chapter_2/exercise_2_02/loop.c @@ -4,6 +4,8 @@ int main(void) { char s[MAXLINE]; + int c; + int i = 0; // int i; // int c; @@ -13,21 +15,26 @@ int main(void) { // s[i] = c; // } - int i = 0; - int loop = 1; - while (loop) { - char c = getchar(); - - if (i >= (MAXLINE - 1) || c == '\n' || c == EOF) { - loop = 0; + while (1) { + if (i >= MAXLINE - 1) { + break; } - s[i++] = c; + c = getchar(); + + if (c == '\n') { + break; + } else if (c == EOF) { + printf("\n"); + break; + } else { + s[i++] = c; + } } s[i] = '\0'; - printf("%s", s); + printf("%s\n", s); return 0; } From fab0bb284860fcdb0a83b4e16460592b0a6a1334 Mon Sep 17 00:00:00 2001 From: "Daniel (Ohkimur) Costrasel" Date: Wed, 10 Dec 2025 16:29:00 +0200 Subject: [PATCH 2/2] Refactor loop implementation to avoid logical operators - Added comments to clarify the approach and potential pitfalls of using multiplication instead of logical operators. --- chapter_2/exercise_2_02/loop.c | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/chapter_2/exercise_2_02/loop.c b/chapter_2/exercise_2_02/loop.c index ef9494c..b958e4d 100644 --- a/chapter_2/exercise_2_02/loop.c +++ b/chapter_2/exercise_2_02/loop.c @@ -2,19 +2,22 @@ #define MAXLINE 1000 +/* + * K&R Exercise 2-2: Write a loop equivalent to: + * for (i = 0; i < lim - 1 && (c = getchar()) != '\n' && c != EOF; ++i) + * s[i] = c; + * without using && or ||. + * + * Note: Using * instead of && is unsafe because it doesn't short-circuit, + * causing getchar() to be called even when the buffer is full or EOF is + * reached. + */ + int main(void) { char s[MAXLINE]; int c; int i = 0; - // int i; - // int c; - // for (i = 0; (i < MAXLINE - 1) * ((c = getchar()) != '\n') * (c != EOF); - // ++i) - // { - // s[i] = c; - // } - while (1) { if (i >= MAXLINE - 1) { break; @@ -25,7 +28,6 @@ int main(void) { if (c == '\n') { break; } else if (c == EOF) { - printf("\n"); break; } else { s[i++] = c; @@ -38,10 +40,3 @@ int main(void) { return 0; } - -// NOTE: The multiplication operation could work in this case because each -// expression is evaluated as a 1 or 0 (true or false), and a multiplication -// between expressions can have the value 1 only if all the expressions are -// true. However, the order of multiplication is not guaranteed to be sequenced -// as with logical operations. So, this is could cause serious problems -// depending on how the compiler deals with multiplication.