How do I print an n-line diamond in C #? Practical explanation

Source: Internet
Author: User


The idea of solving problems: First we print a diamond of n rows, the general diamond is odd line (look at a little), so we print out is an odd line of diamond, generally this form:






problem-solving ideas: We can think of the diamond as two parts, as the above a positive triangle and the following an anti-triangular composition, and then we can print out separately.


Console.WriteLine ("Enter a positive integer greater than 2"); / / at least 3 lines to produce a diamond, enter an even diamond is this even number minus 1 line
            Int n = Convert.ToInt32(Console.ReadLine()); for (int i = 1; i <= (n + 1) / 2; i++) //Print the upper part of the diamond
            { for (int j = (n - 1) / 2; j >= i; j--)
                { //Print spaces
                    Console.Write(" ");
                } for (int k = 1; k <= i * 2 - 1; k++)
                { //Print the "*" number, the i-th line has i*2-1 "*"
                    Console.Write("*");
                }
                Console.WriteLine();
            } for (int i = (n - 1) / 2; i >= 1; i--)//Printing the part below the diamond is the same as the above part
            { for (int j = i - 1; j < (n - 1) / 2; j++)
                {
                    Console.Write(" ");
                } for (int k = 1; k <= i * 2 - 1; k++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            } 

If there is something wrong with the

, please advise us and welcome your questions.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.