Python/C/C++/JAVA

Moderate Practice Programs with Code and Concept

By D.S

Floyd's Triangle

Floyd's triangle is a fascinating pattern that has been replicated using four of the most popular programming languages, including C, C++, Python, and Java. It is a right-angled triangle pattern with natural numbers arranged in rows such that each row consists of one more number than the previous row. This creates an endearing pattern that starts with one element on top and builds up to a length that can be defined by the user. In C and C++, Floyd's triangle can be programmed using for loops, while Python makes use of simple print statements to achieve the same effect. Java requires specific syntax to create Floyd's Triangle. Each language creates the pattern in its unique way but at the core is a common algorithmic approach used to generate the sequence of numbers that make up this pattern.

(a.) C Code

#include <stdio.h>

int main() {
  int n, num = 1;
  printf("Enter the number of rows for Floyd's Triangle: ");
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= i; j++) {
          printf("%d ", num);
          num++;
      }
      printf("
");
  }
  return 0;
}
      
Output:-
Enter the number of rows for Floyd's Triangle: 4
1
2 3
4 5 6
7 8 9 10

(b.) C++ Code

#include <iostream>
using namespace std;

int main() {
  int n, num = 1;
  cout << "Enter the number of rows for Floyd's Triangle: ";
  cin >> n;
  for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= i; j++) {
          cout << num << " ";
          num++;
      }
      cout << endl;
  }
  return 0;
}
      
Output:-
Enter the number of rows for Floyd's Triangle: 4
1
2 3
4 5 6
7 8 9 10

(c.) Python Code

n = int(input("Enter the number of rows for Floyd's Triangle: "))
num = 1
for i in range(1, n + 1):
  for j in range(1, i + 1):
      print(num, end=" ")
      num += 1
  print()
Output:-
Enter the number of rows for Floyd's Triangle: 4
1
2 3
4 5 6
7 8 9 10

(d.) Java Code

import java.util.Scanner;

public class FloydsTriangle {
  public static void main(String[] args) {
      int n, num = 1;
      Scanner input = new Scanner(System.in);
      System.out.print("Enter the number of rows for Floyd's Triangle: ");
      n = input.nextInt();
      for (int i = 1; i <= n; i++) {
          for (int j = 1; j <= i; j++) {
              System.out.print(num + " ");
              num++;
          }
          System.out.println();
      }
  }
}
Output:-
Enter the number of rows for Floyd's Triangle: 4
1
2 3
4 5 6
7 8 9 10