Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create Pyramid with decremental value

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

     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--;
   }
  }
}

>Solution :

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading