Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Write a program in C# Sharp to create a pyramid pattern as shown below. The top of the pyramid starts with a 1, the second row contains two 2s, then three 3s and so on. The user must provide the number of rows as input. The output below will appear if the user’s input is 4.
   1 
  2 2 
 3 3 3 
4 4 4 4


What I have tried:

C#
//Declare Main Variables
            int noOfRows;

if (radioButton1.Checked)
            {
                //Convert Text Box TOINT32
                noOfRows = Convert.ToInt32(textBox1.Text);
                string line = "" ; // for individual output
                
                for (int i = 1; i <= noOfRows; i++) 
                {
                    line = line + i;

                    richTextBox1.SelectionAlignment = HorizontalAlignment.Center;
                    richTextBox1.Text += line + "\n";
                    

                }
            }


my code shows me this result

   1
  1 2
 1 2 3
1 2 3 4
Posted
Updated 14-May-17 21:09pm
v2
Comments
[no name] 14-May-17 21:34pm    
Yeah.... you need another for loop
Richard MacCutchan 15-May-17 3:09am    
As you can see you are just appending each digit to the line each time round the loop. What you should be doing is creating a new string using only the current digit.

I'd suggest to start here: 10 different Number Pattern Programs in C# – CsharpStar[^]
There you'll find an explanation of 10 different ways of building pyramid. You need to use pattern 2.

Good luck!
 
Share this answer
 
Think about your other program (pyramid Diamond). What would you have to change to replace stars with the number of of stars per line ?

When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900