Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

Write a Java program to print Floyd’s triangle?

To print Floyd’s triangle in Java, use two nested loops: an outer loop that iterates over the rows and an inner loop that prints as many consecutive numbers as the current row index. A running counter, starting at 1, is printed and then incremented on every step, producing a right-angled triangle of natural numbers.

What Is Floyd’s Triangle?

Floyd’s triangle is a right-angled triangular array of natural numbers, named after Robert Floyd. It is filled row by row, left to right, beginning with 1. The first row has one number, the second row has two, and the nth row contains n consecutive integers. Because numbers are never repeated, the last value in the triangle equals the total count of numbers printed.

A five-row Floyd’s triangle looks like this:

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

The total count of numbers for n rows follows the formula n(n+1)/2. For 5 rows that is 5(6)/2 = 15, which is exactly the last number shown above. This makes Floyd’s triangle a favourite in coding interviews and beginner Java pattern exercises.

Java Program Using a For Loop

The cleanest approach uses nested for loops. The outer loop runs from 1 to the number of rows, while the inner loop runs from 1 to the current row number, printing and incrementing a shared counter.

import java.util.Scanner;

public class FloydTriangle {
    public static void main(String[] args) {
        int rows, number = 1;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows: ");
        rows = sc.nextInt();

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(number + " ");
                number++;
            }
            System.out.println();
        }
        sc.close();
    }
}

Output:

Enter the number of rows: 5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

The key detail is that the inner loop condition is j <= i, not a fixed value. This is what makes each row one number longer than the previous one.

Java Program Using a While Loop

The same logic can be expressed with while loops when you prefer explicit counter management. You initialize the counters before the loop, test the condition, and increment inside the body.

public class FloydTriangleWhile {
    public static void main(String[] args) {
        int rows = 5, number = 1;
        int i = 1;
        while (i <= rows) {
            int j = 1;
            while (j <= i) {
                System.out.print(number + " ");
                number++;
                j++;
            }
            System.out.println();
            i++;
        }
    }
}

Reverse Floyd’s Triangle

A popular variation prints the widest row first. You simply reverse the outer loop so it counts down from the number of rows to 1, while the inner loop still runs up to the current row length.

public class ReverseFloyd {
    public static void main(String[] args) {
        int rows = 5, number = 1;
        for (int i = rows; i >= 1; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print(number + " ");
                number++;
            }
            System.out.println();
        }
    }
}

If you want to practise more Java fundamentals like these, the Java interview questions hub covers loops, patterns, and data structures with worked examples.

Common Mistakes and Troubleshooting

  • Fixed inner loop bound: writing j <= 1 instead of j <= i prints one number per row instead of a triangle. Always tie the inner loop to the current row index.
  • Resetting the counter: declaring number inside the outer loop restarts it at 1 every row. Declare it once, before the loops, so it keeps incrementing.
  • Missing line break: forgetting System.out.println() after the inner loop prints everything on a single line.
  • Off-by-one rows: starting the outer loop at 0 or using i < rows can drop or add a row. Prefer i = 1; i <= rows.
  • Not closing Scanner: leaving the Scanner open triggers resource-leak warnings; call sc.close() when input reading is done.

Conclusion

Floyd’s triangle is a compact exercise that cements how nested loops and running counters work in Java. Once you understand that the inner loop bound tracks the current row and a single counter carries across rows, you can produce the standard, reverse, or while-loop variants with confidence. It is a small program, but the loop discipline it teaches scales to far more complex problems.

Frequently Asked Questions

What is Floyd’s triangle in Java?

Floyd’s triangle is a right-angled triangular array of natural numbers filled row by row, starting from 1. The nth row contains n consecutive numbers. In Java it is printed using two nested loops, one controlling the rows and one controlling the numbers in each row.

What is the formula for the total numbers in Floyd’s triangle?

For n rows, Floyd’s triangle contains n(n+1)/2 numbers in total. For example, 5 rows contain 5(6)/2 = 15 numbers, and the last number printed always equals that total, since numbering is continuous from 1.

How do you print Floyd’s triangle without user input?

Replace the Scanner input with a hardcoded variable such as int rows = 5. The nested loop logic stays identical, so the program prints a fixed-size triangle without reading anything from the console, which is handy for quick tests.

Can Floyd’s triangle be printed using a while loop?

Yes. Any for-loop version can be rewritten with while or do-while loops. You initialize counters before the loop, check the condition at the top, and increment inside the body to produce exactly the same triangle output.

What is the difference between Floyd’s triangle and Pascal’s triangle?

Floyd’s triangle fills rows with consecutive natural numbers, while Pascal’s triangle fills each cell with binomial coefficients where every value is the sum of the two numbers above it. They look similar but use very different generation logic.

Why is Floyd’s triangle a common interview question?

It tests understanding of nested loops, counter management, and pattern logic in just a few lines of code, making it a fast, reliable way for interviewers to assess a candidate’s grasp of Java control flow.

Related Questions

Test Your Website on 3000+ Browsers

Get 100 minutes of automation test minutes FREE!!

Test Now...

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

...

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests