We can print * tree using For loop.
for (int i = 1; i <= 10; i++)
{
for (int j = i; j > 0; j--)
{
Console.Write("*");
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine();
for (int i = 10; i > 0; i--)
{
for (int j = i; j > 0; j--)
{
Console.Write("*");
}
Console.WriteLine();
}
Explanation
The first loop (for (int i = 1; i <= 10; i++)) iterates from 1 to 10, controlling the number of rows in the tree.
- The nested loop (for (int j = i; j > 0; j--)) is responsible for printing asterisks. The number of asterisks in each row decreases with j, starting from i and ending at 1.
- Console.WriteLine(); is used to move to the next line after each row of asterisks.
After the first loop, two empty lines (Console.WriteLine();) are printed to separate the two trees.
The second loop (for (int i = 10; i > 0; i--)) iterates from 10 to 1, controlling the number of rows in the tree.
- Similar to the first loop, the nested loop (for (int j = i; j > 0; j--)) is responsible for printing asterisks. The number of asterisks in each row decreases with j, starting from i and ending at 1.
- Again, Console.WriteLine(); is used to move to the next line after each row of asterisks.
Result