Search code examples
c#consolenested-loops

how to draw in the console (c#)


recently in IT class we were provided with a simple console program that used a nested loop to draw a right angled triangle. I don't really understand what is happening in this piece of code. could someone explain how it works and how to create other shapes in the console? here's the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Task_4
{
    class nestedLoop
    {
        static void Main(string [] args)
        {
            int i, j;
            i = j = 0;
            for (i = 1; i <= 5; i++)
            {
                for (j = 1; j <= i; j++)
                {
                    Console.Write('*');
                }
                Console.Write("\n");
            }
            Console.ReadLine();
        }
    }
}

Solution

  • There are two for loops, each loop has a variable, i or j assigned to it that will increase by one, until it reaches its upper limit, (i <= 5) or (j <= i). Using this logic, the first loop i is 1 so j will just be 1, then we do the loops again, this time i is 2 so j will run twice, and so forth, below is a small example

    Loop 1, i = 1 j = 1 *

    Loop 2, i = 2 j = 2 **

    Loop 3, i = 3 j = 3 ***

    Loop 4, i = 4 j = 4 ****

    Loop 5, i = 5 j = 5 *****

    So once we have drawn the stars we end up with this.

    Square

    For(int i = 0; i < 5; i++)
    {
       For(int j = 0; j < 5; i++)
          Console.Write("*");
    }
    

    High rectangle

    For(int i = 0; i < 10; i++)
    {
       For(int j = 0; j < 5; i++)
          Console.Write("*");
       Console.Write("\n");
    }
    

    Long rectangle

    For(int i = 0; i < 5; i++)
    {
       For(int j = 0; j < 10; i++)
          Console.Write("*");
       Console.Write("\n");
    }