Answer L11

#include <stdio.h>
#include <stdlib.h>

/* Puzzle L11 -- print the ODD integers from 1 to n, five per line.
|
|  End the last line with a single "\n" regardless of how many
|  integers are on it.
*/

int main()
{
  int j;
  const int n = 53;
  
  for (j=1; j<=n; j+=2 )
  {
    printf("%3d", j);
    if ( j%10==9 ) printf("\n");
  }
  if ( (j-2)%10 != 9 ) printf("\n");
	
  return 0;
}

Comments: Again, the problem is to decide when to output the "\n". This decision is made by examining the integers that end each line, and noticing that each one ends with '9'. You might be happier maintaining a separate count of the integers that have been printed:

  int count = 0;
  for (j=1; j<=n; j+=2 )
  {
    printf("%3d", j);
    count++ ;
    if ( count%5 == 0 ) printf("\n");
  }
  if ( count%5 != 0 ) printf("\n");  
  


Back to Puzzle Home