DEV Community

Muhammadh Ahzem
Muhammadh Ahzem

Posted on

Creating a Symmetrical Star Pattern in Dart

Hey everyone!

I recently worked on a fun coding challenge to generate a symmetrical star pattern using Dart. Here's the pattern I wanted to create:

 *
  **
   ***
    ****
     *****
      ******
       *******
        ********
         *********
          **********
         *********
        ********
       *******
      ******
     *****
    ****
   ***
  **
 *
Enter fullscreen mode Exit fullscreen mode

After some trial and error, I came up with the following solution:

void main() {
  int n = 10; // Height of the pattern

  // Print the upper half of the pattern
  for (int i = 1; i <= n; i++) {
    print(" " * (i - 1) + "*" * i);
  }

  // Print the lower half of the pattern
  for (int i = n - 1; i > 0; i--) {
    print(" " * (n - i) + "*" * i);
  }
}
Enter fullscreen mode Exit fullscreen mode

How It Works:

  1. The first loop generates the upper half of the pattern, starting with 1 star and incrementing up to 10 stars, each line indented with increasing spaces.
  2. The second loop creates the lower half of the pattern, starting from 9 stars down to 1 star, maintaining the symmetry by increasing the leading spaces.

Key Takeaways:

  • This exercise helped me reinforce my understanding of nested loops and string manipulation in Dart.
  • By carefully controlling the number of spaces and stars in each iteration, we can create visually appealing patterns.

Feel free to try it out and let me know if you have any suggestions for improvement!

Happy coding! 🌟

Top comments (0)