A triangular number is formed by the addition of consecutive
integers starting with 1. For example,
1+2=3
1+2+3=6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
Thus, 3, 6, 10, 15, are triangular numbers.
Write a program in Java to display all the triangular numbers
from 3 to n, taking the value of n as an input.
Triangular Number in Java
A triangular number is the sum of the first natural numbers. It follows the formula:
Variable Description Table
Variable Name Data Type Description
n int Input number for which the triangular number is to be found.
triangularNum int Stores the computed triangular number using the formula.
Algorithm
1. Start
2. Take an integer input n from the user.
3. Compute the triangular number using the formula:
4. Print the computed triangular number.
5. End
Java Implementation
import java.util.Scanner;
public class TriangularNumber {
public static void main(String[] args) {
// Create Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Prompt the user for input
System.out.print("Enter a number to find its triangular number: ");
int n = scanner.nextInt();
// Compute the triangular number
int triangularNum = (n * (n + 1)) / 2;
// Display the result
System.out.println("The " + n + "th triangular number is: " +
triangularNum);
// Close the scanner
scanner.close();
}
}
Example Execution
Input:
Enter a number to find its triangular number: 5
Output:
The 5th triangular number is: 15
This program efficiently computes the triangular number for any given integer input using the
direct mathematical formula.