Table of Contents
In this post, we will see how to print Floyd’s triangle in java.
Problem
You need to print Floyd’s triangle as below for n=5.
Floyd’s triangle
****************
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
****************
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Floyd’s triangle in java
Let’s create class "FloydTriangleMainExample.java" as below
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 |
package org.arpit.java2blog; /* Program: It Prints Floyd's triangle based on user inputs * */ import java.util.Scanner; public class FloydTriangleMainExample { public static void main(String args[]) { int rows; int counter = 1; int currRowCount; //To get the user's input Scanner input = new Scanner(System.in); System.out.println("Enter the number of rows for floyd's triangle:"); rows = input.nextInt(); System.out.println("Floyd's triangle"); System.out.println("****************"); for ( currRowCount = 1 ; currRowCount <= rows ; currRowCount++ ) { for ( int j = 1 ; j <= currRowCount ; j++ ) { System.out.print(counter+" "); //Incrementing the number value to print counter++; } //For new line on row change System.out.println(); } input.close(); } } |
When you run above program, you will get below output:
Enter the number of rows for floyd’s triangle:
6
Floyd’s triangle
****************
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
6
Floyd’s triangle
****************
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
That’s all about printing floyd’s cycle in java.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.