Search code examples
c#for-loopnested-for-loop

How to print reverse number pyramid like this one in c#?


i was trying to do thsi bellow pattern but didn't understand it

1
3 2
6 5 4
10 9 8 7

this i what the basic increment number pattern i did

int counterNumPattern = 1;
      
        for(int i = 1; i <= 4; i++)
        {
            for(int j=1;j<=i; j++)
            {
                Console.Write( counterNumPattern++);

               
                

            }
            Console.WriteLine();
        }

Solution

  • Try to decide the first number for each line. You should be able to find some law in the sequence {1,3,6,10,...}. And Then, do decrement instead of increment.

    I wrote as code:

    const int NumberOfLines = 5;
    
    //
    int FirstNumberForLine = 0;
    for( int i=1; i<=NumberOfLines; ++i )
    {
        FirstNumberForLine += i;    //This is the law I found
    
        int Number = FirstNumberForLine;
        for( int j=1; j<=i; ++j )
        {
            Console.Write( Number-- );  //Decrement
            Console.Write( " " );   //Maybe need space
        }
        Console.WriteLine();
    }