Monday, 7 April 2014

C#.NET - Programming code to generate pyramid or triangle with '*' character

Today you will learn how to generate a pyramid or triangle with characters. Generally you may get this type of requirement in interview to test your coding skills.

Here I created one class in Console Application. Save this as a *.cs file and run it within your Console Application.


C# code to generate pyramid with characters

using System;
using System.Text;

class PrintPyramid
{
    static void Main()
    {
        // Ask for the number to generate pyramid.
        Console.Write("Please enter number to generate triangle: ");
        // Get the input value.
        var noOfRows = Convert.ToInt64(Console.ReadLine());

        // Generate pyramid with the given value.
        GenerateTriangle(noOfRows, '*');

        // Wait for the response from command line.
        Console.ReadLine();
    }

    // Method to generate pyramid
    private static void GenerateTriangle(long noOfRows, char charForTriangle)
    {
        // Create an instance of type StringBuilder to store spaces.
        var sbSpaces = new StringBuilder();

        // Add Spaces to the StringBuilder.
        for (int spaces = 1; spaces < noOfRows; spaces++)
        {
            sbSpaces.Append(" ");
        }

        // Take initial row value as 1.
        var noPrint = 1;
        for (long number = 1; number <= noOfRows; number++)
        {
            // Print spaces first.
            Console.Write(sbSpaces);

            // Print 'X' in a single line to generate proper pyramid.
            for (long i = 1; i <= noPrint; i++)
            {
                Console.Write(charForTriangle);
            }

            // After printing one line come to second line.
            Console.WriteLine();

            // Increment noPrint value to add more 'X' to line.
            noPrint += 2;

            // Each time remove one space from StringBuilder to generate pyramid.
            if (sbSpaces.Length > 0)
                sbSpaces.Remove(0, 1);
        }
    }
}

Output:
















No comments: