1

I feel like the answer so simple but I just can't figure out what it is. I have an multidimensional array such as this:

    int [][] number = 
    {{ 10, 15, 11, 13, 72, 87, 266},
        { 50, 65, 80, 94, 12, 134, 248}, 
        { 1, 2, 1, 9, 1, 39, 26}, 
        { 13, 20, 76, 4, 8, 72, 28}, 
        { 2, 1, 29, 2, 12, 907, 92}, 
        { 16, 4, 308, 7, 127, 1, 52}
    };

I'm trying to add up all the integers in the each array index and display it at the end so what I thought up of is this

int total=0;
    for (int k=0;k<6;k++){
    for (int i=0;i<7;i++){

    total=number[k][i]+total;}}
    System.out.println(total);

What I noticed is that it will add up all the numbers in the entire array. But how do I stop it at the end of each index?

2 Answers 2

1

Your question is not clear . But from what I understood you must do

for (int k=0;k<6;k++){
   int total=0;
   for (int i=0;i<7;i++){
      total=number[k][i]+total;}
   System.out.println(total);}

It will print sum of all rows

Sign up to request clarification or add additional context in comments.

Comments

0

Couldn't the loop be like this:

for (int k = 0; k < 6; k++) {
  int total = 0;
  for (int i = 0; i < 7; i++) {
    total += number[k][i];
  }
  System.out.println(total);
}

Assuming I get what you mean by stop it at the end of each index.

And better should it be if you parametrize your loops to fit in each dimension length:

for (int k = 0; k < number.length; k++) {
  int total = 0;
  for (int i = 0; i < number[k].length; i++) {
    total += number[k][i];
  }
  System.out.println(total);
}

2 Comments

Yes, that's what I meant, sorry for not explaining myself correctly
So since I got it right, I suppose the answer solves your problem so you can accept it and even upvote it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.