Answer to Exercise 2-2, page 42
Solutions by "Flippant Squirrel" :-) and Craig Schroeder
Exercise 2-2 discusses a for loop from the text. Here it is:
for(i=0; i<lim-1 && (c=getchar()) != '\n' && c != EOF; ++i)
s[i] = c;
Write a loop equivalent to the for loop above without using && or || .
#include <stdio.h>
#define MAX_STRING_LENGTH 100
int main(void)
{
/*
for (i = 0; i < lim-1 && (c=getchar()) != '\n' && c != EOF; ++i)
s[i] = c;
*/
int i = 0,
lim = MAX_STRING_LENGTH,
c;
char s[MAX_STRING_LENGTH];
while (i < (lim - 1))
{
c = getchar();
if (c == EOF)
break;
else if (c == '\n')
break;
s[i++] = c;
}
s[i] = '\0'; /* terminate the string */
return 0;
}
Here's a Category 1 solution from Craig Schroeder, which is not so much exegetic as - um - cute. :-)
#include <stdio.h>
#define lim 80
int main()
{
int i, c;
char s[lim];
/* There is a sequence point after the first operand of ?: */
for(i=0; i<lim-1 ? (c=getchar()) != '\n' ? c != EOF : 0 : 0 ; ++i)
s[i] = c;
return s[i] ^= s[i]; /* null terminate and return. */
}
'The C Programming Language' 카테고리의 다른 글
Chapter 2 - Types, Operators and Expressions 4 (0) | 2009.03.25 |
---|---|
Chapter 2 - Types, Operators and Expressions 3 (0) | 2009.03.25 |
Chapter 2 - Types, Operators and Expressions 1 (0) | 2009.03.25 |
Chapter 1 - A Tutorial Introduction 24 (0) | 2009.03.25 |
Chapter 1 - A Tutorial Introduction 23 (0) | 2009.03.25 |