Java Triangle

Some Java for your Christmas present…

Here is a short Java program to calculate triangular numbers,
(the sequence: 1 3 6 10 15 21 … ).


/********************************************
* Program to calculate triangular numbers
* inefficiently
* Mathew Peet
* Christmas 2009
*
*********************************************/

public class Triangular {
public static long tri(int n) {
int total = 1;
for (int i = 1; i <=n; i++)
total = total + (i+1);
return total;
}

public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + tri(i));
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s