Example 3_9 Nesting of loop statements

Topic description 

Create a C# Windows application, enter the number of triangle rows, and print the effect as shown.


1> First add 2 Label controls, 1 TextBox, and 1 Button control to Windows Forms. The main property settings of each control are listed in the following table.

controls Attributes property settings controls Attributes property settings
label1 Text Triangle rows: textBox1 Name txtNum
label2 Text "" button1 Name btnOk

Name lbShow
Text Print

2> Double-click the "btnOk" button in the form design area, the system automatically adds the "Click" event and the corresponding event method for the button, and then edit the code in the source code view .

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Test3_9
{
    public partial class Test3_9 : Form
    {
        public Test3_9()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            int n = Convert.ToInt32(txtNum.Text);
            StringBuilder sb = new StringBuilder();
            int i, j;
            for (i = 0; i <= n; i++)
            {
                for (j = 1; j <= n - i; j++)
                {
                    sb.Append(" ");
                }
                for (j = 1; j <= 2 * i - 1; j++)
                {
                    sb.Append("*");
                }
                sb.Append("\n");
            }
            lblShow.Text = sb.ToString();
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324815331&siteId=291194637