C Program to print Floyd’s triangle

1

Floyd’s triangle is a triangle with first natural numbers.

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

Following C program prints Floyd’s triangle with n lines.

C

#include <stdio.h>

void printFloydTriangle(int n)
{
   int i, j, val = 1;
   for (i=1; i<=n; i++)
   {
       for (j=1; j<=i; j++)
         printf("%d ", val++);
       printf("\n");
   }
}

int main()
{
    printFloydTriangle(6);
    return 0;
}

Java

// Java program to print
// Floyd's triangle
    
class Test
{
    static void printFloydTriangle(int n)
    {
       int i, j, val = 1;
       for (i=1; i<=n; i++)
       {
           for (j=1; j<=i; j++){
             System.out.print(val+" ");
             val++;
           }
           System.out.println();
             
       }
    }
         
    // Driver method
    public static void main(String[] args) 
    {
        printFloydTriangle(6);
    }
}

Python3

# Python3 program to print
# Floyd's triangle
def loydTriangle(n):

    val = 1
    for i in range(1, n + 1):

        for j in range(1, i + 1):
            print(val, end =" ")
            val+= 1
        
        print("")

loydTriangle(6)

# This code is contributed by
# Smitha Dinesh Semwal

PHP

<?php
// PHP code to print Floyd's Triangle

// Function to display Floyd's Triangle
function FloydsTriangle($n)
{
    $val = 1;
    
    // loop for number of lines
    for($i = 1; $i <= $n; $i++)
    {
        // loop for number of elements
        // in each line
        for($j = 1; $j <= $i; $j++)
        {
            print($val." ");
            $val++;
        }
        print("\n");
    }
}

// Driver's Code
$n = 6;
FloydsTriangle($n);

// This code is contributed by akash7981
?> 


Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



1 Average Difficulty : 1/5.0
Based on 4 vote(s)