-
Basic Java question
Hello all,
Forgive the novice question but, I'm having some trouble visualizing what's happening in the array, see code below. More specifically in the code pt[i-1][j-1] + pt[i-1[[j]. I'm getting hung up on the fact that in the first for-loop i is set to 0 and in the second loop it looks like i is still set to 0 and pt[0-1[i-1] + pt[0-1][1] is a valid reference. What am I not seeing, can someone explain?
Thanks for the help.
public int[][] pascalTriangle( int n)
{
int[][] pt = new int[n][];
for(int i = 0; i < n; i++){
pt[i] = new int[i+1]; // Construct row i
pt[i][0] = 1; // Leftmost value of row i.
for( int j = 1; j < i; j++){
//System.out.println("pt[i-1]= "+ pt[i-1][j-1]);
pt[i][j] = pt[i-1][ j-1 ] + pt[i-1][j];// Sum 2 entries above.
}
pt[i][i] = 1; // Rightmost value of row i.
}
return pt;
}
-
Re: Basic Java question
I am not getting what incorrect you have done but still i would like to recommend you that you should try to execute this program as i have tried it and worked well. :P
Code:
public class PascalTriangle {
public static void main(String args[]) {
int x = 6;
int triangle[][] = new int[x][x];
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
triangle[i][j] = 0;
}
}
for(int i = 0; i < x; i++) {
triangle[i][0] = 1 ;
}
for (int i = 1; i < x; i++) {
for (int j = 1; j < x; j++) {
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
}
}
for (int i = 0; i < x; i++) {
for(int j=0;j<=i;j++) {
System.out.print(triangle[i][j]+ " ");
}
System.out.println();
}
}
}
-
Re: Basic Java question
hey i think you are trying to make the pascal triangle, so just try this one may it will help you to improve further.
public class Pascal {
public static int[][] Rows(int p){
int[][] ptm = new int[p][];
for (int z = 0; z < p; z++) {
ptm[z] = new int[z + 1];
ptm[z][0] = 1;
for (int q = 1; q< z; q++) {
ptm[z][q] = ptm[z - 1][q - 1] + ptm[z - 1][q];
}
ptm[z][z] = 1;
}
return ptm;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("usage: java " + Pascal.class.getName() + " rows");
System.exit(1);
}
int p = Integer.parseInt(args[0]);
if (p > 0) {
int[][] pascal1 = Rows(n);
for (int[] row1 : pascal1) {
for (int w : row1) System.out.print(w + " ");
System.out.println("");
}
}
}
}
Page generated in 1,717,952,095.44064 seconds with 10 queries