Hi.
First of all, I am new to java and I am having some problems in understanding arrays.

I was asked to do the following program.

2 5 9 8 7
3 4 8 5 3
7 6 9 6 3
8 9 5 3 2
1 3 1 5 6

That is a multidimensional array.
I need to sum the elements from the array that are right from the diagonal
(5 9 8 7 8 5 3 6 3 2)
and
sum the elements from the array that are left from the diagonal
(3 7 6 8 9 5 1 3 1 5)

I know how to sum all the elements from the array, but not certains like in that case.

I want to understand arrays. I would like that you give me just hints of how to do it, not the code itself.

Thanks in advance

PS: Sorry for the English, it isn't my natural language

Well, you have a row index and a column index (call them i and j respectively), and you know the number of rows and the number of columns. For the left side, the elements to the left of the diagonal are the ones you are interested in and those are defined as those array elements where the row index is greater than the column index. For the right side of the diagonal, you are interested in those elements where the row index is less than the column index. So you're going to have a nested loop:

for (int i = ?; i < ?; i++) // rows
{
     for (int j = ?; ? < ?; j++)
     {
         // add element (i,j) to the sum
     }
}

Fill in the question marks for the correct loop parameters. These question marks will depend on whether you are doing the left or right side. Note the elements you are interested in above and design your loops so that all of those index combinations and only those index combinations go through the loop.

Thanks, sounds logic.
Here is my final code:

class ArraysM{

public static void main (String args[]) {
	ArraysM. fillArrayB ();
}
public static void fillArrayB(){
	int a[][] = new int [3][3];
	for(int i=0;i<3;i++){
		for (int j=0;j<3;j++){
			System.out.println("Enter the element "+i+ "," +j);
			a[i][j] = Lectura.readInt();
		}
	}
	ArraysM.sum2(a);
	ArraysM.sum1(a);
	
		}
public static void sum2 (int a[][]){
	int acum = 0;
	for (int i=0;i<3;i++){
		for (int j=0;i>j;j++){
			acum = acum+a[i][j];
			
				}
			}
	System.out.println("");
	System.out.println("Elements of region 1: "+acum);

	}
public static void sum1 (int a[][]){
	int acum = 0;
	for (int j=0;j<3;j++){
		for (int i=0;i<j;i++){
			acum = acum+a[i][j];
			
				}
			}
	System.out.println("");
	System.out.println("Elements of region 2: "+acum);

	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.