FLOYD’S TRIANGLE USING C and C++

Floyd's triangle programming using C & C++

What is Floyd's Triangle

Floyd's triangle is a right-angled triangular pattern of natural numbers, named after Robert Floyd who described it in his book "Non-Programmer's Introduction to Programming". It consists of n rows, where each row contains consecutive natural numbers starting from 1 in the first row to n in the nth row. The triangle is formed by aligning the first number of each row with the left edge of the triangle.

For example, a Floyd's triangle of 5 rows will look like this:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Floyd's triangle can be useful for a variety of programming applications, such as testing loop structures, generating numerical patterns, and displaying output in a visually pleasing way.

Print Floyd's Triangle of n rows using C

#include <stdio.h>
 
int main()
{
    int n, i, j, k = 1;
    printf("Enter the number of rows: ");
    scanf("%d", &n);
 
    for (i = 1; i <= n; i++)
    {
        for (j = 1; j <= i; j++)
        {
            printf("%d ", k);
            k++;
        }
        printf("\n");
    }
 
    return 0;
}

Print Floyd's Triangle of n rows using C++

#include <iostream>
using namespace std;
 
int main()
{
    int n, i, j, k = 1;
    cout << "Enter the number of rows: ";
    cin >> n;
 
    for (i = 1; i <= n; i++)
    {
        for (j = 1; j <= i; j++)
        {
            cout << k << " ";
            k++;
        }
        cout << endl;
    }
 
    return 0;
}
Both of these codes take the number of rows of the Floyd's Triangle as input and use nested loops to generate the triangle by incrementing a counter variable. The outer loop controls the number of rows, and the inner loop controls the number of elements in each row. The variable k is used to keep track of the current value being printed.

Comments

Popular posts from this blog

TRAVELING SALESMAN USING BRANCH AND BOUND TECHNIQUE

Arrays

TRAVELING SALESMAN USING BRANCH AND BOUND TECHNIQUE