Reputation: 2785
So I asked a question earlier here, in which the numbers in an array should be added together till the length of 12.
Now, how would I add the remaining numbers, lets say
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, 10,20};
from the above I get an answer of
1804.9
780.0
1804.9
but it missed the last two numbers 10 and 20
, how would I add both of them if the count is not equal to 12?
Thanks.
Upvotes: 1
Views: 168
Reputation: 26671
class Sum {
public static void main(String[] arguments) {
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, 10, 20
};
double sum = 0.0;
double remainder = 0.0;
for (int i = 0; i < addMe.length; i++) {
if (i >= (addMe.length - addMe.length / 12)) {
remainder = remainder + addMe[i];
}
if (i % 12 == 0 && i != 0) {
System.out.println(sum);
sum = 0;
}
sum += addMe[i];
}
System.out.println("Remainder sum: " + remainder);
}
}
Upvotes: 1
Reputation: 21
You have to print it out of the loop, since it becomes empty before it can be evenly divided by 12, it doesn't successfully print, that is why you add the print statement outside of the loop, so when it finishes, it will print the remaining sum.
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, 10,20};
double sum=0.0;
int y = 0;
for(int i=0;i<addMe.length;i++)
{
if(i%12==0 && i!=0)
{
y++;
System.out.print(y+": "+sum+"\n");
sum=0;
}else{
sum +=addMe[i];
}
}
y++;
System.out.println(y+": "+sum);
Output
1: 1804.9
2: 770.0
3: 20.0
Upvotes: 1
Reputation: 6181
Try this: (If you require to print sum
within loop, else the above answer by @L-X is better solution).
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];
if(i==addMe.length-1)
System.out.println(sum);
}
Upvotes: 1
Reputation: 4375
modify this much, You are adding all the numbers , it just you are not printing the last sum if elements are less than 12
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];
}
System.out.println(sum);//Just add this outside the loop
Upvotes: 3