I just created this method for a 2D array but is throwing me an exception. I wan
ID: 3755154 • Letter: I
Question
I just created this method for a 2D array but is throwing me an exception.
I want it to do this with a certain number of rows.
This is my method:
private void createTriangle()
{
//Initializing the array with 1 more than the size of the rows
array = new int[rows][];
array[0] = new int[1];//declaring number of elements in row
array[1] = new int[2];//declaring number of elements in row
array[0][0] = 1;// Store a 1 in the first column of the first row
// Store a 1 in the first column of every from the second one on
array[1][0] = 1;
// Store a 1 in the last column of every row from the second one on
array[1][1] = 1;
for (int i = 2; i <= rows - 1; i++)
{
int j = 0;
array[i] = new int[i+1];
array[i][j]= 1;
}
for (int i = 2; i<= rows - 1; i++)
{
int j = i;
array[i][j] = 1;
}
/**
* Generating numbers from the third row for the triangle
* and adding it to the corresponding array positions.
*/
for (int i = 2; i <= rows - 1; i++)
{
// loop to store the sum of the values in the previous row,
// previous column and previous row, same column
for (int j = 1; j < array[i].length - 1; j++)
{
//number= number in (previous row, previous column)
//+ number in (previous row, next column).
array[i][j] = array[i - 1][j - 1] + array[i - 1][j];
}
}
}
Explanation / Answer
Please check with the code below. Let me know if still you have any issues. I'll help.
Please do rate if it was helpful. Thank you.
private void createTriangle()
{
//Initializing the array with 1 more than the size of the rows
array = new int[rows][];
array[0] = new int[1];//declaring number of elements in row
array[1] = new int[2];//declaring number of elements in row
array[0][0] = 1;// Store a 1 in the first column of the first row
// Store a 1 in the first column of every from the second one on
array[1][0] = 1;
// Store a 1 in the last column of every row from the second one on
array[1][1] = 1;
for (int i = 2; i <= rows - 1; i++)
{
int cols = i + 1;
array[i] = new int[cols];
array[i][0]= 1; //store 1 in 1st column
array[i][cols-1] = 1; //store 1 in last column
}
/**
* Generating numbers from the third row for the triangle
* and adding it to the corresponding array positions.
*/
for (int i = 2; i <= rows - 1; i++)
{
// loop to store the sum of the values in the previous row,
// previous column and previous row, same column
for (int j = 1; j < array[i].length - 1; j++)
{
//number= number in (previous row, previous column)
//+ number in (previous row, next column).
array[i][j] = array[i - 1][j - 1] + array[i - 1][j];
}
}
}