Search code examples
c#for-loopnested-loops

C# Number Triangle Ascending and Descending by 2


I found a way to display the top half of the triangle ending at 18 with a nested for loop. I cannot figure out how to display the bottom half in a nested for loop as well (it has to be in a nested for loop). Also, how to make the the colors interchange from green and red? Any tips?

enter image description here

Here's what I have:

int n1, n2, n3;

// Top Triangle nested for loop
for (n1 = 2; n1 <=18; n1++)
{
    for (n2 = 2; n2 <= n1; n2++)
    {
        Console.Write("{0} ", n2);
        n2++;
    }
    n1++;
    Console.WriteLine();
}

// Bottom triangle nested for loop
// This is where I'm stuck

Solution

  •         for (n1 = 2; n1 <= 18; n1++)
            {
                for (n2 = 2; n2 <= n1; n2++)
                {
                    Console.Write("{0} ", n2);
                    n2++;
                }
                n1++;
                Console.WriteLine();
            }
            for (n1 = 2; n1 <= 18; n1++)
            {
                for (n2 = 2; n2 <= 18 - n1; n2++)
                {
                    Console.Write("{0} ", n2);
                    n2++;
                }
                n1++;
                Console.WriteLine();
            }