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?
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];
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With