Answer L21

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

/* Puzzle A21 -- print a pine tree of stars */
int main()
{
  int row, j, spaces, stars;
  int n=12;
  
  /* The triangle */
  for ( row=0; row<n; row++ )
  {
    stars = 2*row+1;
    spaces = (2*n-1-stars)/2;
    for ( j=0; j<spaces; j++ )
      printf(".");
    for ( j=0; j<stars; j++ )
      printf("*");
    for ( j=0; j<spaces; j++ )
      printf(".");
    printf("\n");
  }
  
  /* the trunk */
  stars = 2*(n/8)+1;
  spaces = (2*n-1-stars)/2;
  for ( row=0; row<n/3; row++ )
  {
    for ( j=0; j<spaces; j++ )
      printf(".");
    for ( j=0; j<stars; j++ )
      printf("*");
    for ( j=0; j<spaces; j++ )
      printf(".");
    printf("\n");
  }
  printf("\n");

  return 0;
}

Comments: The two pieces of the tree (triangle and trunk) correspond to two sections of the code. Each section is code you have seen before. In programming, big parts are created by combining little parts, and even bigger parts are created by combining further. This notion is probably the most important idea in computer science.



Back to Puzzle Home