Dilyan
Dilyan

Reputation: 37

Drawing a pyramid with a for loop in c#

I need to draw this a pyramid using numbers. Last number should be the number entered "n". With an n = 7 ,i should have this:

1

2 3

4 5 6

7

With an n= 10, i should have this:

1

2 3

4 5 6

7 8 9 10

Where am I wrong with my code?

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

namespace Pyramid
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());

            int cnt = 1;

            for (int row = 0; cnt <= n; row++)
            {
                for (int col = 0; col <= row && cnt <= n; col++)
                {
                    Console.WriteLine("{0}", cnt);
                    cnt++;
                }
                Console.WriteLine();
            }


        }
    }
}

Upvotes: 0

Views: 742

Answers (1)

Hari Prasad
Hari Prasad

Reputation: 16956

You are almost there, just replace Console.WriteLine inside the inner for loop to Console.Write.

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

Console.WriteLine writes the data, followed by the current line terminator, that causes your output to write in next line.

Upvotes: 5

Related Questions