#include <stdio.h>
/*
   Generate Grey codes -- an enumeration of the integers of N bits so that
   successively listed integers differ in only 1 bit position in their
   binary representation.
   The Grey codes of N bits can be obtained from the Grey codes of N-1 bits
   as follows:
	0 (Grey codes of N-1 bits).
	1 (Grey codes of N-1 bits, in reverse).
*/
typedef int Grey_code;
typedef enum{fwd,rev} direction;
void Each_GC(int N, direction D, void Yield(Grey_code)!) {
   if (N == 1)
      if (D == fwd) {
	 Yield(0); Yield(1);
	 }
      else {
	 Yield(1); Yield(0);
	 }
   else {
      void P(Grey_code C) {
	 Yield( (1 << (N-1)) | C);
	 }
      if (D == fwd) {
	 Each_GC(N-1,fwd,Yield);
	 Each_GC(N-1,rev,P);
	 }
      else {
	 Each_GC(N-1,fwd,P);
	 Each_GC(N-1,rev,Yield);
	 }
      }
   }

void main() {
   int N;
   for (N = 1; N <= 4; N++) {
      void P(Grey_code C) {
	 void Print_binary(int C, int Field_width) {
	    if (Field_width > 1) Print_binary(C >> 1, Field_width-1);
	    printf("%1d",C&1);
	    }
	 printf("%*c",8-N,' ');
	 Print_binary(C,N);
	 printf("\n");
	 }
      printf("Grey code of %d bits:\n",N);
      Each_GC(N,fwd,P);
      }
   }
