KnowledgeBoat Logo

Java Number Programs (ISC Classes 11 / 12)

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.

Java

Java Iterative Stmts

ICSE

33 Likes

Answer

import java.util.Scanner;

public class KboatTriangularNumbers
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");
        int n = in.nextInt();
        
        if (n < 3) {
            System.out.println("Value of n should be greater than or equal to 3");
            return;
        }
        
        System.out.println("Triangular Numbers from 3 to " 
                            + n + ":");
        int sum = 3; //First Triangular Number
        for (int i = 3; sum <= n; i++) {
            System.out.println(sum);
            sum += i;
        }
    }
}

Output

BlueJ output of 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.

Answered By

12 Likes