![]() |
VOOZH | about |
Christmas is a season of joy and festivities, and what better way to celebrate it as a programmer than by creating a Christmas tree pattern using C++? In this article, we will learn how to print a Christmas tree pattern of desired height using simple nested loops in C++.
The tree consists of a series of pyramid structures stacked together, with a trunk at the bottom to complete the festive look. This complex task can be simplified by breaking the tree into parts can make it a bit easy.
Printing Upper Part (Pyramids): printTop() Function
First, we take 4 variables to control the tree structure
- height: Specifies the number of pyramid levels in the tree. It is given by the user, but the default value is set to 5.
- width: Starting width for the topmost pyramid level is 5. This grows as we move down the tree.
- space: Controls the alignment of the tree. It starts as width * 5, ensuring the tree is centered.
- x: Controls the width of each row in the whole pyramid. It ensure the tree widens as it goes down.
The pyramid part is then printed by:
- Outermost loop prints the level/number of the pyramid
- Inner loop iterates through each row of the pyramid.
- Innermost loops are used to manage spaces and asterisks for each row.
- The first innermost loop handles printing spaces before the asterisks to centre them.
- The second innermost loop prints the asterisks in a pyramid pattern.
Printing Lower Part (Trunk): printTrunk() Function
- A loop is used to print the lower part of the tree, which represents the tree trunk. It prints 4 rows for the trunk.
- First inner loop is used to align the trunk centrally below the tree by printing spaces.
- Second inner loop prints a fixed number of stars (4) to form the rectangular trunk.
The whole program is enclosed inside a class ChristmasTree and printTrunk() and printTop() functions are called by the print() function.
Output:
*
* *
* * *
* * * *
* * * * *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * *
* * * *
* * * *
* * * *