CS 1073 Introductory Programming
|
// i 5-i 2*i+1
chars(' ',5); chars('*',1); // 0 5 1
System.out.println();
chars(' ',4); chars('*',3); // 1 4 3
System.out.println();
chars(' ',3); chars('*',5); // 2 3 5
System.out.println();
chars(' ',2); chars('*',7); // 3 2 7
System.out.println();
chars(' ',1); chars('*',9); // 4 1 9
System.out.println();
chars(' ',0); chars('*',11); // 5 0 11
System.out.println();
The program prints:
*
***
*****
*******
*********
***********
I put a little "table" at the right, showing values of i going from 0 to 5, and showing what 5-i and 2*i+1 would then be.
Using this insight, you can write a for loop, letting i take on values from 0 to 5 inclusive. This loop prints the same tree.
for (int i = 0; i <= 5; i++) {
chars(' ', 5-i); chars('*', 2*i+1);
System.out.println();
}
Now use a variable n in place of 5 (an n that you read in), and the tree is printed at any size. You might ask where the functions 5-i and 2*i+1 come from, but they are also relatively easy. We know there has to be some linear function that gives the right values, so just using a few values, it is easy to construct the correct function.