Finding Triangular Numbers in Java
Definition of Triangular Number
Triangular number of a natural number n is the sum of all natural numbers from 1 to n. For example, Triangular number of 5 = 1 + 2 + 3 + 4 + 5 = 15. Mathematically,
It is known as triangular numbers since it is the total number of dots in a triangle with n dots on a side. For example, Triangular number of 5 can be represented in the following triangle,
Finding Triangular Number of a Number in Java
The following Java program finds the triangular number of a given number. It uses a simple loop to find the sum,
/* Printing Triangular number for a number in Java */ public class TriangularNumber { public static void main(String[] args) { int number = 6; int triangular = 0; for(int i = 1;i<=6;i++) { triangular = triangular + i; } System.out.println("Triangular Number for "+number+" is "+triangular); } }
Finding Triangular Numbers of a Range of Numbers
The following Java program finds triangular numbers for a range of natural numbers,
/* Printing Triangular number for a range of numbers in Java */ public class TriangularNumbers { public static void main(String[] args) { int starting_number = 1; int ending_number = 10; System.out.println("List of Triangular Numbers "); for (int i = starting_number; i <= ending_number; i++) { int triangular = 0; for (int j = 1; j <= i; j++) { triangular = triangular + j; } System.out.println(i + " = " + triangular); } } }
Another way of calculating Triangular number is to use the following formula,
Triangular number of n = (n*(n+1))/2.
/* Printing Triangular number for a number in Java using n*(n+1)/2 formula */ public class AlternateTriangularNumber { public static void main(String[] args) { int number = 9; int triangular = number * (number+1)/2; System.out.println("Triangular Number for "+number+" is "+triangular); } }