"The C Programming Language", 2nd edition, Kernighan and Ritchie

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. */
}



Back to index





You are visitor number - call again soon!