Nov 14, 2016

K & R : Exercise 2.2 - loop equivalent

K & R : Exercise 2.2 - loop equivalent

Problem

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

for(i=0; i < lim -1 && (c=getchar()) != '\n' && c != EOF; ++i)
  s[i] = c;

Solution

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

No comments :

Post a Comment