Path: utzoo!utgpu!water!watmath!clyde!att!pacbell!lll-tis!helios.ee.lbl.gov!pasteur!agate!ig!uwmcsd1!mailrus!iuvax!pur-ee!a.cs.uiuc.edu!p.cs.uiuc.edu!kenny
From: kenny@p.cs.uiuc.edu
Newsgroups: comp.lang.c
Subject: Re: Should I convert FORTRAN code to C?
Message-ID: <77200036@p.cs.uiuc.edu>
Date: 7 Jul 88 01:10:00 GMT
References: <2742@utastro.UUCP>
Lines: 78
Nf-ID: #R:utastro.UUCP:2742:p.cs.uiuc.edu:77200036:000:2338
Nf-From: p.cs.uiuc.edu!kenny    Jul  6 20:10:00 1988


In an article written yesterday, I present:

		PROGRAM 7.
>[main program still hasn't changed]
>grdgen (df, nlev)
>     register int df;		/*  no. of degrees of freedom */
>     register int nlev;		/*  no. of levels each df */
>{
>  register int i;
>  register int j;
>  register int totaldfm1 = df - 1;
>  static int value [MAXDF];	/* to hold current values of all df's */
>
>  for (;;) {
>    while (df >= 0) {		/* Set up initial values */
>      i = 0;
>      value [df--] = i;
>    }
>
>    for (j = 0; j < totaldfm1; ++j)	/* Print a node */
>      printf ("%d ", value [j]);
>    printf ("%d\n", value [j]);
>
>    for (;;) {			/* Develop another node */
>      if (df >= totaldfm1) return;
>      i = value [++df] + 1;
>      if (i < nlev) {
>	value [df--] = i;
>	break;
>      }
>    }
>  }
>}

And I don't know what posessed me.  The program can be simplified
quite a bit.  One of the assignments to i is useless, and a `break'
statement can be drawn out of a loop.  While no version is truly
final, I'd prefer the following:

		PROGRAM 7A.
[main program still hasn't changed]
grdgen (df, nlev)
     register int df;		/*  no. of degrees of freedom */
     register int nlev;		/*  no. of levels each df */
{
  register int i;
  register int j;
  register int totaldfm1 = df - 1;
  static int value [MAXDF];	/* to hold current values of all df's */

  for (;;) {
    while (df >= 0)		/* Set up initial values */
      value [df--] = 0;

    for (j = 0; j < totaldfm1; ++j)	/* Print a node */
      printf ("%d ", value [j]);
    printf ("%d\n", value [j]);

    do {			/* Develop another node */
      if (df >= totaldfm1) return;
      i = value [++df] + 1;
    } while (i >= nlev);
    value [df--] = i;
  }
}

BTW, the program analysis techniques that I've been promulgating *do*
come up with this fragment;  I was just careless running them by hand
(The fact that they *can* be automated doesn't mean that they *have*
been automated).

The more I look at this version, the more I like it.  The loop breaks
down into three steps: initialize, print a node, increment some index.
It's particularly satisfying that a series of essentially mechanical
steps was able to derive an iterative version as clean as this from
the original recursive version.  I doubt I'd have done as well setting
out to write an iterative version by hand.