'How to create this christmas tree pattern?

e

so I'm trying to create this Christmas tree pattern using the loop, if the number increase, the number of layers as well as lines will increase, so how to do this ples



Solution 1:[1]

The things to note in your example are:

  • On level N of the tree, there are N layers
  • On layer M of a level, there are 2M - 1 leaves

Here's an implementation in C++:

#include <iostream>

void drawChristmasTree(const int base_height, const int num_levels) {
  // Max layer width is the width of the bottom most leaf-layer of the tree
  // Bottom most layers of each level follow the pattern: 1, 3, 5, ..., (2n - 1)
  const int max_layer_width = (2 * num_levels) - 1;

  // Tree levels
  for (int level = 1; level <= num_levels; ++level) {
    // Layers of a level
    // There are N layers on level N
    for (int layer = 1; layer <= level; ++layer) {
      // Number of leaves on each layer of the level follow the pattern: 1, 3, 5, ..., (2n - 1)
      const int num_leaves = (2 * layer) - 1;
      const int num_spaces =  (max_layer_width / 2) - (num_leaves / 2);

      // Draw the spaces
      for (int i = 0; i < num_spaces; ++i) {
        std::cout << " ";
      }
      // Draw the leaves
      for (int i = 0; i < num_leaves; ++i) {
        std::cout << "*";
      }
      // Draw line break
      std::cout << std::endl;
    }
  }

  // Draw the base
  const int num_spaces_for_base = max_layer_width / 2;
  for (int i = 0; i < base_height; ++i) {
    // Draw spaces
    for (int j = 0; j < num_spaces_for_base; ++j) {
      std::cout << " ";
    }
    // Draw base
    std::cout << "*" << std::endl;
  }
}

int main() {
  drawChristmasTree(/*base_height=*/5, /*num_levels=*/5);
  return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1