Lecture notes on iteration

For my CE 21 class. The problem discussed earlier was, draw a triangle of stars given the length for a side of the triangle n. It can be illustrated as follows for n = 3.

*
* *
* * *

The next task is to center the triangle:

  *
 * *
* * *

Then we want to be able to print a diamond

  *
 * *
* * *
 * *
  *

This C++ code is one of the solutions to the problem:

#include <iostream>
int main()
{
  int n;
  std::cin &gt;&gt; n;
  int i = 1;
  // upper triangle
  while( i &lt;= n )
  {
    int space = n - i;
    for(int j = 1 ; j &lt;= space ; j++ )
    {
      std::cout &lt;&lt; " ";
    }
    int j = 1;
    while( j &lt;= i )
    {
      std::cout &lt;&lt; "* ";
      j++;
    }
    std::cout &lt;&lt; std::endl;
    i++;
  }
  // lower triangle
  i = n - 1;
  while( i &gt;= 1 )
  {
    int space = n - i;
    for(int j = 1 ; j &lt;= space ; j++ )
    {
      std::cout &lt;&lt; " ";
    }
    int j = 1;
    while( j &lt;= i )
    {
      std::cout &lt;&lt; "* ";
      j++;
    }
    std::cout &lt;&lt; std::endl;
    i--;
  }
  return 0;}

For the homework, answer the Challenge section of the lecture slides on iterations:

  • Draw a pine tree with 3 sections
  • Each section should have n lines of stars
  • The start of the next section should have one less star than the end of the previous section
  • Add n lines of single asterisks for a stand

Example for n = 3:

      *
     * *
    * * *
     * *
    * * *
   * * * *
    * * *
   * * * *
  * * * * *
      *
      *
      *

Technorati Tags: , , , ,

Related Posts Related Websites

0 Response to “Lecture notes on iteration”


  • No Comments

Leave a Reply