Assignment 1
My first java program. This is the java source code to create Pascal's Triangle, and you may also download it
When you download it you will need to use the JDK compiler from SUN to run the java applet.
import corejava.*;
public class Mathew1
{
//Function will calculate the numbers for pascal's triangle.
public static long pascaltriangle(int n, int r)
{
long temp = 1;
int i;
for (i = 1; i <= r; i++)
{
temp = temp * n / i;
n--;
}
return temp;
}//end pascaltriangle
public static void main(String[] args)
{ int i=0;
int j=0;
int lines=0;
int NumberofLines=0;
//Get the number of lines to print out
//of the Pascal's Triangle
NumberofLines = Console.readInt
("Enter the number of lines to calculate or -1 to exit: ");
while(NumberofLines != -1)
{
System.out.println();
long[][] factor = new long[NumberofLines + 1][]; //create 2-D array
for (i = 0; i <= NumberofLines; i++)
factor[i] = new long[i + 1];
// fill triangular array
for (i = 0; i < factor.length; i++)
for (j = 0; j < factor[i].length; j++)
factor[i][j] = pascaltriangle(i, j);
// print out array into pascal's triangle
int count = 34; //center out the triangle on the screen
for (i = 0; i < factor.length; i++)
{
for(int k = 0; k < count; k++)
System.out.print(" ");
for (j = 0; j < factor[i].length; j++)
Format.printf("%6d", factor[i][j]);
count = count - 3;
System.out.println();
}
System.out.println();
NumberofLines = Console.readInt
("Enter the number of lines to calculate or -1 to exit: ");
}//end while loop
} //end main
} //end Mathew1