P3: Print Patterns

Simple Right-Angled Triangle Program

Let's create a program to print a right-angled triangle of user specified height:

Console.Write("Enter the height of the triangle: ");
int triangleHeight = int.Parse(Console.ReadLine());

for (int row = 1; row <= triangleHeight; row++)
{
    // Print stars for each row
    for (int star = 1; star <= row; star++)
        Console.Write("*");

    Console.WriteLine();
}

Explanation

  • In the right-angled triangle program, there are two nested loops:

    • The outer loop (row) iterates over each level (or row) of the triangle.

    • The inner loop (star) prints the number of stars corresponding to the current row number.

  • Each row has a number of stars equal to its row number, creating a right-angled triangle pattern.

This right-angled triangle program is a straightforward and effective way to teach beginners about nested loops, with a clear visual output that makes it easy to understand the concept.

Pyramid printing program

Console.Write("Enter the height of the pyramid: ");
int pyramidHeight = int.Parse(Console.ReadLine());

for (int level = 1; level <= pyramidHeight; level++)
{
    // Print spaces for alignment
    for (int space = pyramidHeight; space > level; space--)
        Console.Write(" ");
    
    // Print stars
    for (int star = 1; star <= level * 2 - 1; star++)
        Console.Write("*");

    Console.WriteLine();
}

Explanation

  1. The program starts by asking the user to specify the height of the pyramid.

  2. It then uses two nested loops:

    • The first loop (outer loop) iterates over the number of levels in the pyramid.

    • The second loop (inner loop) first prints spaces to create the right alignment and then prints the stars to form the pyramid shape.

  3. Each level of the pyramid has an increasing number of stars, forming a pyramid as the loop progresses.

This program is visually engaging and demonstrates the practical use of nested loops, offering a fun way to understand these concepts.

Last updated