Assessment Tool

Lecture 10:  Loops

Content Tested:  Programming with loops

Lecture Content:

Goals:

Assessment Technique:  Programming Activity

Purpose:

This programming activity serves to give students experience writing functions containing loops.

Activity:



More ASCII art!!  We have seen loops in the past two lectures.  This activity gives you the opportunity to write functions to create a picture of a tree like the one shown below.

     *
    ***
     *
    ***
   *****
     *
    ***
   *****
  *******
     |
-----+-----

Note that the tree consists of drawing spaces, stars, a vertical line, a plus sign, and minus signs.  Write a function called print_tree that takes as a parameter the size of the tree.  The size is the number of tiers (or triangles) that make up the tree.  In the above picture, there are 3 tiers.  You may assume that the size of the tree is greater than or equal to 1.

Hints:
1.  Before diving into the code, be sure to design your algorithm -- think about how many spaces and stars are required to print one tier of the tree.
2.  Think about writing a separate function called print_tier that simply prints a single tier of the tree given the number of rows and the center position for the tier.
3.  Use the entire design process -- problem specification, algorithm, function design, implementation, and testing.

Possible Solution

/* print_tree
 * input:  int size
 * output:  none
 * function:  prints tree with size number of tiers
 */

void print_tree(int size){

  int i;                 /* looping variable */

  /* print tiers */
  for(i = 0; i < size; i++){
    print_tier(size, i+2);
  }

  /* print trunk */
  for(i = 0; i < (size + 2); i++){
    printf(" ");
  }
  printf("|\n");

  /* print ground */
  for(i = 0; i < (size + 2); i++){
    printf("-");
  }
  printf("+");
  for(i = 0; i < (size + 2); i++){
    printf("-");
  }
  printf("\n");
}

/* print_tier
 * input:  int size, int num_rows
 * output:  none
 * function:  prints a single tier consisting of a triangle
 * with num_rows rows.  size indicates the centering position
 * of the tier (number of spaces over where tip should start)
 */

void print_tier(int size, int num_rows){

  /* tree is centered size + 2 spaces from the left */
  int i, j;

  for(i = 0; i < num_rows; i++){
    /* space over size + 2 - i spaces */
    for(j = 0; j < (size + 2 - i); j++){
      printf(" ");
    }

    /* print i * 2 + 1 stars */
    for(j = 0; j < (i * 2 + 1); j++){
      printf("*");
    }
    printf("\n");
  }
}

Possible Uses of Activity: