1

I am trying to add every 12 numbers in an array. For example

double[] addMe = {147.04, 147.66, 148.27, 148.89, 149.51, 150.13, 150.76, 151.39, 152.02, 152.65, 153.29, 153.29, 
                10, 20 ,30,40,50,60,70,80,90,100,110,120};

I am able to add all the numbers inside the array by doing the following

double sum = 0;
for (double i : addMe){
                sum += i;
            }
System.out.println(sum);

Which gives me 2584.9.

But I am trying to get sum of every 12 numbers in the array which should give me

1804.84
780.0

How should I do that?

thanks.

1
  • Any reason for the uncheck and answer switch? Commented Sep 24, 2015 at 10:33

2 Answers 2

4
double sum=0.0;
for(int i=0;i<addMe.length;i++)
{
  if(i%12==0 && i!=0)
  {
    System.out.println(sum);
    sum=0;
  }

  sum +=addMe[i];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Close, but your don't want to print for i=0 and you do want to print after the loop.
1

You can keep track of the index and current sum and only output the current sum when the index is 12:

    int index = 0;
    double sum = 0;
    for(double i: addMe){
        index++;
        sum+=i;
        if (index == 12){
            System.out.println(sum);
            index = 0;
            sum = 0;
        }
    }

Comments

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.