Trimming a Tree with Nested Loops

By now, you’ve probably pretty much gotten the hang of all kinds of iterations and how to use while statements, do/while statements, and for loops. It’s a good thing because we’ll be using these techniques a great deal in the rest of Learn How to Program. You can do all kinds of things using loops, and there isn’t all that much you can do without them. So learning to use iterative statements is a crucial step on your journey to becoming a programmer.

But before moving on, let’s look at one final example. It may not be Christmas when you read this book, but quite likely you’re familiar with Christmas trees. This example shows you how to draw a Christmas tree, complete with ornaments, on the screen. As you can see in Figure 4-10, the tree is mostly “drawn” using the letter X, and ornaments are made out of capital letter Os. (Will this really be as much fun as Christmas? I think not.)

click to expand
Figure 4-10: Nested loops are used to draw a tree using Xs and Os.

The point of this example is that it takes three for loops to accomplish the task. Not unlike wooden dolls that you may have seen—you can open up the largest one to find another one inside, which you can, in turn, open—there’s an outermost loop. Within it, there’s another loop, and within that loop there is the innermost loop. Loops that are set up this way are called nested loops. So you can add another line to the song about partridges and pear trees: On a certain day of Christmas, my true love gave to me, one nested loop.

Seriously, folks, before we get to the actual code, let’s look at what each loop does. The outer two loops control the height of the tree and where its width is “stepped back.” (If you look at Figure 4-10, you can see a “step back” in the width of the tree every five rows, which corresponds to the maximum value in the middle loop.)

Each row in the tree is created by writing an HTML <BR>, or line break, tag.

Within the innermost loop, the “tree” and ornaments are drawn by writing X and O characters. X represents the tree’s branches, and O represents ornaments. The positioning of ornaments is determined somewhat at random (so if you refresh your browser, you’ll get a somewhat different layout).

To “Draw” a Tree Using Nested Loops:

Try This at Home
  1. Create the framework for a script within the body of an HTML document:


    By the way, I’ve added a <CENTER> tag to this so that the tree will appear in the middle of the browser.

  2. Declare and initialize the variable width, which controls the number of characters written per line of the tree:

     var width=1; 

  3. Create the scaffolding, or structure, for the outermost for loop:

     for (   ;   ;  )  {    } 

  4. Nest within the outermost loop another loop framework:

     for (   ;   ;  )  {     for (   ;   ;  )     {      }   } 

  5. Create the innermost loop framework within the other two loops:

     for (   ;   ;  )  {     for (   ;   ;  )     {         for (   ;   ;  )         {         }      }   } 


    As a reminder, the increment operator (++) adds one to its operand. So writing i++ is equivalent to the statement i = i + 1.

  6. Fill in the loop conditions:

     for (i=0; i <= 5 ; i++)  {     for (x=0; x<=4; x++)     {        for (y=1; y<=width; y++)      {      ... 

    What this amounts to is that the outermost loop goes from zero to five, including five (from one to six would have been another way to write the same thing); the middle loop goes from zero to four, including four (this would be the same as from one to five); and the innermost loop goes from one to the value of the width variable. This is relatively complex code. You can get a good feeling for what it’s doing by sitting down with pencil and paper and pretending you’re the computer, following directions, and seeing what you draw. It’s also educational to modify the code and see what happens.

  7. Add the logic to the innermost loop that uses the JavaScript random number generator—explained in Chapter 3, “ Using Conditional Statements ” —to write Os and (mostly) spaces followed by Xs:

     for (y=1; y<=width; y++)  {     var Number=Math.random()*10;     var Ornament=Math.round(Number);     if (Ornament<=1)     {        document.write("O");     }     if (Ornament>=2                   )     {         document.write(" X");     }  } 

  8. Below the end of the innermost loop, so that it’s controlled by the middle loop, write a line break and increment the width variable by one:

     document.write("<BR>");  width=width+1; 

    Incrementing the width variable will cause each subsequent, and lower, row of the tree to be one character wider than the previous row.

  9. Below the end of the middle loop, decrement the width variable by two:

     width = width - 2 

    This has the effect of taking two characters off the width of the next tree row each time the middle loop completes—or every five rows— and program control returns to the outermost loop.

Listing 4-4 shows the complete code for this program. If you run it in your browser, you’ll get a Christmas tree that looks pretty much like the one shown in Figure 4-10.

Listing 4.4: Drawing a Christmas Tree Using Nested For Loops

start example
 <HTML> <BODY> <CENTER> <SCRIPT>     var width=1;     for (i=0; i <= 5 ; i++)     {        for (x=0; x<=4; x++)        {           for (y=1; y<=width; y++)           {              var Number=Math.random()*10;              var Ornament=Math.round(Number);              if (Ornament<=1)              {                 document.write("O");              }              if (Ornament>=2)              {                 document.write(" X");              }           }           document.write("<BR>");           width=width+1;        }        width=width-2;     }  </SCRIPT> </CENTER> </BODY> </HTML> 
end example

If you look closely at Figure 4-10, and at the code for the program, you can see that the innermost loop writes the lines. The line break and increment to the width variable in the middle loop are controlling line width in five row groups; every sixth row, the subtraction from the width variable gives the tree an indent.

You can count the rows in the tree and verify that it has 30 rows. This is the product obtained by multiplying the upper bounds of the middle and outer loops.

These numerical values and relationships are essentially arbitrary. I encourage you to play with them to create your own tree!

The important point is that in many programs it is common to see loops within loops—you often need to do this to get the functionality a program requires. It can be a little difficult to keep different loops and how they interact straight. As always, I want to get you off on the right foot, so things will not be hard for you later.

The Christmas tree program is a (I hope) gentle introduction to the concepts and techniques that you need to work with multiple nested loops.

Learn How to Program Using Any Web Browser
Learn How to Program Using Any Web Browser
ISBN: 1590591135
EAN: 2147483647
Year: 2006
Pages: 115
Authors: Harold Davis

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: