Drawing A Pyramid

Lesson 3
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

drawing a pyramid using asterisks (*) in C#:

int num_rows = 5;
for (int i = 1; i <= num_rows; i++)
{
    // print spaces
    for (int j = 1; j <= num_rows - i; j++)
    {
        Console.Write(" ");
    }

    // print asterisks
    for (int k = 1; k <= 2 * i - 1; k++)
    {
        Console.Write("*");
    }

    Console.WriteLine(); // move to next line
}

In this code, we first define the number of rows we want in our pyramid (num_rows is set to 5 in this example). We then use a for loop to iterate through each row.

For each row, we use another for loop to print the appropriate number of spaces before the asterisks. The number of spaces is equal to num_rows - i, where i is the current row number. This ensures that the asterisks are centered in the pyramid.

We then use another for loop to print the asterisks. The number of asterisks is equal to 2 * i - 1, where i is the current row number. This ensures that the number of asterisks increases by 2 for each row.

Finally, we move to the next line using Console.WriteLine() to start a new row in the pyramid. When we run this code, we get the following output:

    *
   ***
  *****
 *******
*********

This is a simple example, but the same concept can be applied to create more complex shapes and patterns using loops.