Sunday, August 16, 2009

Triangular Number Program in Java

Hi friends, today Java Code Online is going to discuss the Java Code for generating the Triangular Numbers up to the entered number of times.

A Triangular Number is one which is the sum of all the numbers starting from 1 up to that particular number. For example if I say the number is 3, then 1+2+3=6, so 6 is the third Triangular Number.

The provided Java code asks the user, to enter the required number of Triangular Numbers, and then generate that many Triangular Numbers starting from 1.

The Java Code is provided below:-

package developer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TriangularNumber {

/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
System.out.println("How many Triangular Numbers are required:");
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
int j = 1;
int num = Integer.parseInt(br.readLine());

for(int i = 1; i<= num; i++)
{
j = i * (i+1)/2;
System.out.print(j + " ");
}
}
}

I hope the above Java Code was helpful to you all. Keep buzzing Java Code Online for more interesting Java information and programs.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.