Write a program to print Floyd triangle in Java :
A Floyd triangle is a right angled triangle that is created by using increasing numbers. For example , following is a Floyd triangle of height 6 :
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
In this example, we will learn how to print a Floyd triangle in Java.
Steps to print Floyd triangle :
-
Take the height from user
-
Run a loop : that will run from 1 to the height
-
Inside the loop, run one more loop . That will run same time as the outer loop’s count. That means , if the outer
loop is on step 1, inner loop will run 1 time. Outer loop is on step 2, inner loop will run 2 times.
-
Save one variable with initial value 1. Print this value on each iteration of the inner loop.
-
After the inner loop complets, print a new line .
Program :
/*
* Copyright (C) 2017 codevscolor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.ArrayList;
import java.util.Scanner;
/**
* Example Class
*/
public class ExampleClass {
/**
* System.out.println utility method
*
* @param value : value to print
*/
static void print(String value) {
System.out.print(value);
}
/**
* main method for this class
*/
public static void main(String[] args) {
int height;
Scanner scanner = new Scanner(System.in);
print("Enter Height for the triangle : ");
height = scanner.nextInt();
//count will increase each time and we will print it
int count = 1;
for (int i = 1; i <= height; i++) {
for (int j = 1; j <= i; j++) {
print(count + " ");
count ++;
}
System.out.println();
}
}
}
Sample Output :
Enter Height for the triangle : 5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15