Home »
.Net »
C# Programs
C# - Floyd's Triangle Program
Here, we are going to learn how to print Floyd's triangle in C#?
By Nidhi Last updated : April 15, 2023
Floyd's Triangle
Floyd's triangle is a triangular array of natural numbers used in computer science education. It is named after Robert Floyd. It is defined by filling the rows of the triangle with consecutive numbers, starting with a 1 in the top left corner. [Source]
Example
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Here, we will Floyd's triangle using nested loops on the console screen.
C# program to print Floyd's triangle
The source code to print Floyd's triangle is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# - Floyd's Triangle Program
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.
C# Basic Programs »