Open In App

C++ Program to Print Christmas Tree Using Pyramid

Last Updated : 24 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This program prints a Christmas tree with a specified height and width. It consists of two main parts: the upper part that forms the tree’s triangular shape and the lower part that represents the tree trunk.

Approach to Print Christmas Tree

Christmas tree creation is a complex task but breaking the tree into parts can make it a bit easy. The parts broken are mentioned below:

Printing Upper Part (Pyramids):

  • A loop iterates through each row of the pyramid.
  • Inner loops are used to manage spaces and asterisks for each row.
  • The first inner loop handles printing spaces before the asterisks to center them.
  • The second inner loop prints the asterisks in a pyramid pattern.

Printing Lower Part (Branch):

  • Another loop is used to print the lower part of the tree, which represents the tree trunk.
  • Similar to the upper part, inner loops are used to manage spaces and print asterisks.

Program to Print Christmas Tree Using Pyramid

Below is the implementation of the topic mentioned above:

C++




// C++ Program to implement
// Cristmas Tree Pattern 
#include <iostream>
  
using namespace std;
  
// Driver Class
class PrintChristmasTree {
public:
    // Value 5 is permanently provided to height variable
    static const int height = 5;
  
    // Main Function
    static int main()
    {
        // Assigning Width
        int width = 5;
  
        // Assigning Space
        int space = width * 5;
  
        int x = 1;
  
        // Code to Print Upper Part of the Tree i.e.
        // Pyramids.
        for (int a = 1; a <= height; a++) {
            for (int i = x; i <= width; i++) {
                for (int j = space; j >= i; j--)
                    cout << " ";
  
                for (int k = 1; k <= i; k++)
                    cout << "* ";
  
                cout << endl;
            }
  
            x = x + 2;
            width = width + 2;
        }
  
        // Printing Branch of Christmas Tree
        for (int i = 1; i <= 4; i++) {
  
            for (int j = space - 3; j >= 1; j--)
                cout << " ";
  
            for (int k = 1; k <= 4; k++)
                cout << "* ";
  
            cout << endl;
        }
        return 0;
    }
};
  
// Main function
int main()
{
    PrintChristmasTree::main();
    return 0;
}


Output:

Christmas Tree Using Pyramid

Complexity of the Above Method:

Time complexity: O(h*w*w) for given height h and width w
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads