Jul 21, 2014

K&R Exercise 1.6 Expression getchar() != EOF

Problem Statement

Exercise 1-6: Verify that expression getchar() != EOF is 0 or 1.


Lets us assign result of getchar() != EOF to a variable r, and print the integer value of it every time.

#include <stdio.h>

int main()
   int c;
   int r;

   do {
      c= getchar();
      r = (c != EOF);
      printf("c=%d, r=%d\n",c , r);

   return 0;

Output of the above program is

c=97, r=1
c=10, r=1
c=98, r=1
c=10, r=1
c=48, r=1
c=10, r=1
c=-1, r=0

Output needs some explanation -getchar() fetches one character from STDIO and returns it. When a and ENTER is pressed. First ASCII value of 'a' is assigned to c which is 97, since 97 !=0 r value is 1(true). Second character that getchar gets is ENTER key which is ASCII 10. When Ctrl-D is pressed which is EOF the loop is exited with r value as 0.


Next Article - K&R Exercise 1.7 Value of EOF
Previous Article - K&R Exercise 1.5 Temperature conversion reverse order

All Article - K & R Answers

No comments :

Post a Comment