Q:

C# program to print Floyd\'s triangle

belongs to collection: C# Basic Programs | basics

0

C# program to print Floyd's triangle

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | basics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to calculate the multiplication of two ... >>
<< C# program to calculate the multiplication of two ...