Skip to content

Commit 05f1382

Browse files
authored
Merge pull request #97 from kkaname/main
Implemented the code using while loop and without any relational operators
2 parents 396a2cd + fab0bb2 commit 05f1382

File tree

1 file changed

+25
-23
lines changed

1 file changed

+25
-23
lines changed

chapter_2/exercise_2_02/loop.c

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,39 +2,41 @@
22

33
#define MAXLINE 1000
44

5+
/*
6+
* K&R Exercise 2-2: Write a loop equivalent to:
7+
* for (i = 0; i < lim - 1 && (c = getchar()) != '\n' && c != EOF; ++i)
8+
* s[i] = c;
9+
* without using && or ||.
10+
*
11+
* Note: Using * instead of && is unsafe because it doesn't short-circuit,
12+
* causing getchar() to be called even when the buffer is full or EOF is
13+
* reached.
14+
*/
15+
516
int main(void) {
617
char s[MAXLINE];
7-
8-
// int i;
9-
// int c;
10-
// for (i = 0; (i < MAXLINE - 1) * ((c = getchar()) != '\n') * (c != EOF);
11-
// ++i)
12-
// {
13-
// s[i] = c;
14-
// }
15-
18+
int c;
1619
int i = 0;
17-
int loop = 1;
18-
while (loop) {
19-
char c = getchar();
2020

21-
if (i >= (MAXLINE - 1) || c == '\n' || c == EOF) {
22-
loop = 0;
21+
while (1) {
22+
if (i >= MAXLINE - 1) {
23+
break;
2324
}
2425

25-
s[i++] = c;
26+
c = getchar();
27+
28+
if (c == '\n') {
29+
break;
30+
} else if (c == EOF) {
31+
break;
32+
} else {
33+
s[i++] = c;
34+
}
2635
}
2736

2837
s[i] = '\0';
2938

30-
printf("%s", s);
39+
printf("%s\n", s);
3140

3241
return 0;
3342
}
34-
35-
// NOTE: The multiplication operation could work in this case because each
36-
// expression is evaluated as a 1 or 0 (true or false), and a multiplication
37-
// between expressions can have the value 1 only if all the expressions are
38-
// true. However, the order of multiplication is not guaranteed to be sequenced
39-
// as with logical operations. So, this is could cause serious problems
40-
// depending on how the compiler deals with multiplication.

0 commit comments

Comments
 (0)