Hello Coders, In this Java tutorial we are going to discuss the Floyd's triangle pattern using the concept of nested for loop.
Floyd's triangle is a right angle triangle that is made by using number that are in increasing format.
Below is the example for floyd's triangle which contains height=7 :
1.Take a value size from the user and store it a variable(int size).
2.Create variable that holds the value of rows(i) and columns(j) and also initialize a variable with 1 (count=1).
3.As we are using nested for loops, the Outer loop is for rows and the Inner loop is for columns.
4.The first for loop will count the varaible using i as 1 and checks whether i<=n.Same with the second nested for-loop checks till j=1 till j<=i.
5.After every successful iteration the count value is incremented and placed at particular matrix position.
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int size; System.out.println("Enter the size: "); size=sc.nextInt(); int count=1; for(int i=1;i<=size;i++){ for(int j=1;j<=i;j++){ System.out.print(count+" "); count++; } System.out.println(); } } }
Enter the size:7
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
Hope you understood the concept and code clearly,if not do comment below.
Also checkout different question's on Java pattern :
Submitted by Sohail Chand Kalyani (sohailkalyani)
Download packets of source code on Coders Packet
Comments