The C Programming Language, 2nd Edition, by Kernighan and Ritchie
Exercise 2.02 on page 42

Exercise 2-2 discusses a for loop from the text. Here it is:
  for(i<nowiki>=</nowiki>0; i<lim-1 && (c<nowiki>=</nowiki>getchar()) !<nowiki>=</nowiki> '\n' && c !<nowiki>=</nowiki> EOF; ++i)
    s[i] <nowiki>=</nowiki> c;


Write a loop equivalent to the for loop above without using && or || .


Solutions by Flippant Squirrel and Craig Schroeder

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

Personal tools
Tidy_icons
not logged in