C# program to print Floyd's triangle

Here, we are going to learn how to print Floyd's triangle in C#?
Submitted by Nidhi, on October 03, 2020

Here, we will Floyd's triangle using nested loops on the console screen.

Program:

The source code to print Floyd's triangle is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to print Floyd's triangle
using System;

class MathEx
{
    static void Main(string[] args)
    {
        int outer = 1;
        int inner = 1;
        int num   = 1;
        int rows  = 0;

        Console.Write("Enter the number of rows: ");
        rows = int.Parse(Console.ReadLine());

        for (; outer <= rows; outer = outer + 1)
        {
            for (inner = 1; inner < outer + 1; inner++)
            {
                Console.Write(num + " ");
                num = num + 1;
            }
            Console.WriteLine();
        }
    }
}

Output:

Enter the number of rows: 8
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
Press any key to continue . . .

Explanation:

Here, we created a class MathEx that contains a Main() method, In the Main() method we declared 4 variables outer, inner, num, and rows initialized with 1,1,1 respectively. Then read the value of rows from the user.

for (; outer <= rows; outer = outer + 1)
{
    for (inner = 1; inner < outer + 1; inner++)
    {
        Console.Write(num + " ");
        num = num + 1;
    }
    Console.WriteLine();
}

In the above code, we print Floyd's triangle, here the outer loop is executed 1 time for each row and the inner loop is executed to print elements of the row.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.