Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum like zig-zag algorithm

Tags:

java

math

Assuming I have 2 data like this:

x = 1, and {10,20,30}.

I want to sum like this:

1 + 10 = 11, 11 + 20 = 31, and 31 + 30 = 61

My code.

int x = 1;
int[] arr = {10, 20, 30};
int sum = 0;
for (int i = 0; i < arr.length; i++) 
{
    sum = arr[i] + x;
}

I get this:

1 + 10 = 11, 1 + 20 = 21, and 1 + 30 = 31 and so on

How to solve this problem?

like image 457
user2976890 Avatar asked Jul 18 '26 14:07

user2976890


2 Answers

Initialize sum to x, and add the value at arr[i] to sum and don´t set the sum to arr[i] + x.

int sum = x; // You only want to add x once, so just say the sum is equal to x
for (int i = 0; i < arr.length; i++) 
{
    // You didn´t sum the values up, you just said the sum is equal to your 
    // x value plus the element at arr[i]
    sum += arr[i];
}
like image 54
SomeJavaGuy Avatar answered Jul 21 '26 03:07

SomeJavaGuy


You can do this like

int[] arr = {10, 20, 30};
int x = 1;
int sum = x;
for (int i = 0; i < arr.length; i++) 
{
    sum = sum + arr[i];
}

You just have to add new values to previously obtained sum. So it is like sum = sum+next_item

like image 44
RanchiRhino Avatar answered Jul 21 '26 04:07

RanchiRhino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!