Home > Back-end >  Create Pyramid with decremental value
Create Pyramid with decremental value

Time:04-08

I'm trying to create a pyramid in c# using a number input. I know how to create a normal pyramid that counts from 1-20 but I can't seem to find what to change on my code to make it.

Instead of:

      1
     2 2
    3 3 3
   4 4 4 4

I need it to be:

     4
    3 3
   2 2 2
  1 1 1 1

Here's my current code:

using System;  
public class Exercise17  
{  
    public static void Main()
{
   int i,j,spc,rows,k;
   
    Console.Write("\n\n");
    Console.Write("Display the pattern like pyramid with repeating a number in same row:\n");
    Console.Write("-----------------------------------------------------------------------");
    Console.Write("\n\n");   
   
   Console.Write("Input number of rows : ");
   rows= Convert.ToInt32(Console.ReadLine()); 
   spc=rows 4-1;

   for(i=1;i<=rows;i  )
   {
        for(j=spc;j>=1;j--)
        {
          Console.Write(" ");
        }
        for(k=1;k<=i;k  )

        Console.Write("{0} ",i);
        Console.Write("\n");
        spc--;
   }
  }
}

CodePudding user response:

First, you need to reverse the for loop. So that it starts with rows, loops while greater than zero, and decrements and each iteration

  for (i = rows; i > 0; i--)

This is the main part. But you also need to take care of the spaces. So to do this we now need to keep track of how many iterations we have already performed. So we need a new variable initiated before the loop.

int iteration = 1;
for (i = rows; i > 0; i--)
 .....

Then we need to use this, in the loop to output the number. And then increment it afterwards.

for (k = 1; k <= iteration; k  )
    Console.Write("{0} ", i);

iteration  ;

So the whole loop now looks like;

int iteration = 1;
for (i = rows; i > 0; i--)
{
    for (j = spc; j >= 1; j--)
    {
        Console.Write(" ");
    }

    for (k = 1; k <= iteration; k  )
        Console.Write("{0} ", i);
        
    Console.Write("\n");
    spc--;
    iteration  ;
 }    

Now the challenge is, can you try to optimise this further?

CodePudding user response:

Instead of the following:

Console.Write("{0} ",i);

You can write:

Console.Write("{0} ", (rows - i)   1);
  •  Tags:  
  • c#
  • Related