Sunday, September 24, 2023

How to print Floyd's Triangle in Java with Example

There are lots of programming exercises in Java, which involve printing a particular pattern in the console, one of them is printing the Floyd triangle in the console. In the Floyd triangle, there are n integers in the nth row and a total of (n(n+1))/2 integers in n rows. This is one of the most simple patterns to print but helpful in learning how to create other more complex patterns. The key to develop patterns is using nested loops and methods like System.out.print() and println() appropriately. Actually, pattern-based programming tasks are originally designed to master loops in programming.

A good programmer should be able to look at a pattern and break it into nested loops. A more formal definition of Floyd's triangle: "It's a right-angled triangle of an array of natural numbers, which is named after Robert Floyd. 

It is defined by filling the rows of the triangle with consecutive numbers, starting with 1 in the top left corner".

It looks like the following pattern :
1
2  3
4  5  6
7  8  9  10
11  12  13  14  15

Your task is to print this table using nested loops in Java. The main point is to build the logic by yourself, this will help you a lot in the long run.

Also, basic knowledge of essential data structure and algorithms is also very important and that's why I suggest all Java programmers join a comprehensive Data Structure and Algorithms course like Data Structures and Algorithms: Deep Dive Using Java on Udemy to improve their knowledge and algorithms skills.




Java Program to draw Floyd's Triangle

Here is my sample code example to draw a format representing Floyd's triangle. 

This program first asks the user to enter a number of rows till you want to show Floyd's triangle. 

You can use Scanner to get the input from the user and then you can use that number in your logic. The code for printing Floyd's triangle is the method printFloydTriangle(int rows), it takes a number of rows, which is the user input. 


This method uses nested loops, two loop in this case to draw the format of Floyd's triangle. The first loop is used to print a number of rows and the second loop is used to print numbers in the row.


import java.util.Scanner;

/**
* Java program to print Floyd's triangle up-to a given row
*
* @author Javin Paul
*/
public class FloydTriangle {
 
    public static void main(String args[]) {
        Scanner cmd = new Scanner(System.in);
 
        System.out.println("Enter the number of rows of Floyd's triangle, 
                                   you want to display");
        int rows = cmd.nextInt();
        printFloydTriangle(rows);
 
    }
 
    /**
     * Prints Floyd's triangle of a given row
     *
     * @param rows
     */
    public static void printFloydTriangle(int rows) {
        int number = 1;
        System.out.printf("Floyd's triangle of %d rows is : %n", rows);
 
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(number + " ");
                number++;
            }
 
            System.out.println();
        }
    }
 
}
 
Output
Enter the number of rows of Floyd's triangle, you want to display
5
Floyd's triangle of 5 rows is :
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
 
Enter the number of rows of Floyd's triangle, you want to display
10
Floyd's triangle of 10 rows is :
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
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55

That's all about how do you print Floyd's triangle in Java. It's a very good programming exercise to build your foundation on loops especially nested loops. After that, you can also try a couple of other pattern-based programming tasks's e.g. printing Pascal's triangle and some other patterns. 

If you like to do solve some programming problems other than patterns you can also try the following exercises :
  1. How to count occurrences of  a character in String? (Solution)
  2. How to find first non repeated characters from String in Java? (See here for solution)
  3. Write a Program to check if a number is binary in Java? (Solution)
  4. How to remove duplicates from array without using Collection API? (Solution)
  5. Write a Program to calculate Sum of Digits of a number in Java? (Solution)
  6. How to Swap Two Numbers without using Temp Variable in Java? (Trick)
  7. How to check if LinkedList contains loop in Java? (Solution)
  8. Write a Program to Check if a number is Power of Two or not? (Answer)
  9. How to find the middle element of LinkedList in one pass? (See here for Solution)
  10. How to check if a number is Prime or not? (Solution)
  11. Write a Program to calculate factorial using recursion in Java? (Click here for solution)
  12. How to check if a number is Palindrome or not? (Solution)
  13. How to check if Array contains duplicate number or not? (Solution)
  14. How to remove duplicates from ArrayList in Java? (Solution)
  15. Write a Java Program to See if two String are Anagram of each other? (Solution)
  16. Write a Program to find Fibonacci Series of a Given Number? (Solution)
  17. How to check if a number is an Armstrong number or not? (Solution)
  18. Write a Program to prevent Deadlock in Java? (Click here for solution)
  19. Write a Program to solve Producer-Consumer Problem in Java. (Solution)
  20. How to reverse String in Java without using API methods? (Solution)
  21. How to print prime factors of a number in Java? (Solution)
And lastly one question for you? Which one is your favorite Java coding exercise? Palindrome, Prime number, Fibonacci, Factorial or this one? Do let me know in comments.

Feel free to ask any question you may have?

12 comments :

Unknown said...

How to print:0
909
89098
7890987
678909876
56789098765
4567890987654
345678909876543
23456789098765432
1234567890987654321 in java

siva said...

static void printMe(int rows){
for(int i=rows;i>0;i--){
for(int j=i;j<=rows;j++){
System.out.print(j);
}
System.out.print("0");
for(int j=rows;j>=i;j--){
System.out.print(j);
}
System.out.println("");
}
}

Unknown said...

hi what about this ??
1
2*3
4*5*6
7*8*9*10
I tried doing it but the output was like this :((
1*
2*3*
4*5*6*
7*8*9*10*
Thanks

Monir said...

How to print this Floyds triangle without using any loop? And also not using a series of print statement.

Pankaj said...

public static void printFloydTriangle(int limit) {
int breakIndex = 1;
int breakNumber = 1;
for (int i=1 ;;i++) {
System.out.print(i+" ");
if (i == breakNumber) {
System.out.println("");
breakIndex++;
breakNumber = i+breakIndex;
}
if (breakIndex ==limit +1 ) {break;}
}
}

Anonymous said...

program to print 28
27.21
26.20.15
25.19.14.10
24.18.13.09.06
23.17.12.08.05.03
22.16.11.07.04.02.01 with input 7

javin paul said...

That's great @Anonymous, keep going.

Unknown said...

Am having trouble writing a code for displaying a triangle that looks like this
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

Unknown said...

1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
How solve?

Unknown said...

public static void triangle(int rows) {
for (int i = 1; i <= rows; i++) {
for (int j = rows ; j >= i; j--) {
System.out.print(" ");
System.out.print(" " + "*" + " ");
}
System.out.println();
}
}

Anonymous said...

1
2 3
4 5 6
7 8 9 10
11 12 13
14 15
16
How do I solve using while loop?

sammykioko said...

how to print a java floyd's triangle with odd numbers only

Post a Comment