Difference between revisions of "Oh Christmas Tree"

From CompSciWiki
Jump to: navigation, search
 
Line 1: Line 1:
{{1010PrAD|ProblemName=Is it a tree? a rocket? It's source code!
 
|Problem= Evergreens are a great pointy companion around the holidays. Or in the middle of July really. Today your going to draw one with text on the console using System.out. If you despise the idea of Christmas trees, imagine it's an awesome rocket ship!
 
  
 
 
|SideSectionTitle=By Students
 
 
|SideSection=I've actually typed essentially this program back in middle school as part of my computer class. It was super obfuscated so that it really only taught typing, but it was kind of interesting to see the result. Did the Apple ][ actually have a backspace key? I never found it.
 
 
|Solution=So this can be done pretty easily. I use a method that takes two arguments, the char you want to print, and the number of times you want to print it.
 
 
This one function both draws the needle-branch things AND the space needed between the start of the line and where the branches should start.
 
 
Using this one function, build a for loop and use your function to print out a line of asterisks on each iteration. Your output will look something akin to:
 
 
<pre>
 
*
 
**
 
***
 
****
 
*****
 
******
 
</pre>
 
 
Well, that's half the tree anyway. Double that up and you have a brilliantly bushy but lopsided tree. To change the lopsidedness, you'll have to print spaces before the tree. More at the top, less at the bottom. Once you've done that, your output becomes:
 
 
<pre>
 
    **
 
    ****
 
  ******
 
  ********
 
**********
 
************
 
</pre>
 
 
And that's enough of a rocket tree for my liking. For an extra little challenge, try putting a trunk / thrusters on that bad boy.
 
 
|SolutionCode=// Put this in a file named RocketTree.java
 
class RocketTree
 
{
 
private static final int TREE_HEIGHT = 10;
 
 
public static void main(String args[])
 
{
 
for (int a = 0; a < TREE_HEIGHT; a++)
 
{
 
// Make some inital space
 
printChar(TREE_HEIGHT - a, ' ');
 
 
// Draw zee tree
 
printChar(a * 2, '*');
 
 
System.out.println();
 
}
 
 
printChar(TREE_HEIGHT - 2 + 1, ' ');
 
printChar(2, '^');
 
System.out.println();
 
}
 
 
static void printChar(int howMuch, char out)
 
{
 
// Decrement without an assign? You're a madman!
 
for (;howMuch > 0; howMuch--)
 
{
 
System.out.print(out);
 
}
 
}
 
}
 
}}
 

Latest revision as of 18:43, 9 April 2010