Pages

Thursday, December 5, 2019

Java Program to Print or Display Floyd’s Triangle With Example Output

1. Overview


In this programming series tutorial, You'll learn how to create and print Floyd's triangle in java today.  Printing the consecutive numbers in order and right-angled triangle as below is said to be Floyd's Triangle.


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

Formula to find the total number of elements in the Floyds triangle is n * (n+1) / 2 where n is the input that how many lines should be printed in the output. The same formula can be used to calculate the sum of n natural numbers also.

Java Program to Print or Display Floyd’s Triangle With Example Output


Refer: Find Sum of N Natural Numbers Using Arthimetic Formulae.

2. Java Example Program to Print or Display Floyd’s Triangle


package com.java.w3schools.blog.java.program.to;

import java.util.Scanner;

/**
 * 
 * Java Program to Print or Display Floyd’s Triangle With Example Output
 * 
 * @author javaprogramto.com venkatesh
 *
 */
public class FloydTriangle {

 public static void main(String[] args) {

  int totalNoOfRows, number = 1;

  // Reading the input from user.
  Scanner scanner = new Scanner(System.in);
  System.out.println("Enter the number of rows for floyd's triangle:");

  // storing the user input into a variable
  totalNoOfRows = scanner.nextInt();
  System.out.println("Floyd's triangle");
  System.out.println("********************");

  // row number is initialized to 1
  int rowNo = 1;

  for (rowNo = 1; rowNo <= totalNoOfRows; rowNo++) {
   for (int j = 1; j <= rowNo; j++) {
    System.out.print(number + " ");
    // Incrementing the number value
    number++;
   }
   // Moving the pointer to the new line
   System.out.println();
  }

 }

}

Output:

Enter the number of rows for floyd's triangle: 10
Floyd's triangle
********************
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 


Given input is 10 and printed 10 lines of numbers. Use the formula 10 * (10 +1) / 2 = 10 * 11 / 2 = 55. Output has total 55 numbers and the last number also 55.

Below is the output for different input = 7.

Enter the number of rows for floyd's triangle: 7
Floyd's triangle
********************
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 

3. conclusion


In this article, you have learned how to display Floyd's triangle in java and seen the formula to find the number of values and last number in the triangle using n*(n+1)/2.


No comments:

Post a Comment

Please do not add any spam links in the comments section.