Skip to content

Commit c8cbf8a

Browse files
committed
Implemented the solution by using while loop and without using any relational operators
1 parent 396a2cd commit c8cbf8a

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

chapter_2/exercise_2_02/loop.c

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
int main(void) {
66
char s[MAXLINE];
7+
int c;
8+
int i = 0;
79

810
// int i;
911
// int c;
@@ -13,21 +15,26 @@ int main(void) {
1315
// s[i] = c;
1416
// }
1517

16-
int i = 0;
17-
int loop = 1;
18-
while (loop) {
19-
char c = getchar();
20-
21-
if (i >= (MAXLINE - 1) || c == '\n' || c == EOF) {
22-
loop = 0;
18+
while (1) {
19+
if (i >= MAXLINE - 1) {
20+
break;
2321
}
2422

25-
s[i++] = c;
23+
c = getchar();
24+
25+
if (c == '\n') {
26+
break;
27+
} else if (c == EOF) {
28+
printf("\n");
29+
break;
30+
} else {
31+
s[i++] = c;
32+
}
2633
}
2734

2835
s[i] = '\0';
2936

30-
printf("%s", s);
37+
printf("%s\n", s);
3138

3239
return 0;
3340
}

0 commit comments

Comments
 (0)