Jump to: navigation, search

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=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 || .


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


Pilcrow 05:01, 28 July 2011 (UTC)

         i=0;
         while(i<lim-1) {
              if((c=getchar()) != '\n') {
                   if(c != EOF) {
                         s[i] = c;
                   }
              }
              i++;
         }



Valentin's try for Category 0 solution

#include <stdio.h>
#define MAXSTRING 1001
#define END 1
#define CONTINUE 0

int check_conditions(void);

int i, lim = MAXSTRING, c;

int main(void)
{
  extern  int i, lim, c;
  char s[MAXSTRING];

  for (i = 0; check_conditions() != END; ++i)
    s[i] = c;
  s[i] = '\0';

  printf("%s\n",s);

  return 0;
}

int check_conditions(void)
{
  extern int i, lim, c;
  if (i < lim - 1)
    if ((c=getchar()) != '\n')
      if (c != EOF)
	return CONTINUE;
  return END;
}
Personal tools
Personal tools
Tidy_icons
not logged in