Reputation: 1
I'm working on an assignment for a beginning Java course and I am completely stuck on this problem.
Write a program that computes the sum of the differences of pairs of numbers in an array. For example if the array is [2, 3, 7, 8, 9, 12] the sum of the differences of pairs is (2-3) + (7-8) + (9-12) ** we are not allowed to use built in Java functions.
Here is what I have so far.. (I know it is terrible)
public static void main(String[] args)
{
int[] A = {3, 4, 5, 6, 1, 2};
int total = 0;
int sum = 0;
for(int i = 0; i < A.length; i++)
{
for(int j = i+1; j < A.length; j++)
sum = (A[i] - A[j]);
}
System.out.println(sum);
}
}
Upvotes: 0
Views: 1180
Reputation: 11
When you use that nested cycle you're doing this:
i = 0,
j = 1,
sum = 3 - 4;
// next cycle,
i = 0,
j = 2,
sum = 3 - 5;
// etc...,
i = 1,
j = 2,
sum = 4 - 5,
// etc..;
Which means for each value of A[i]
you're making the difference of A[i]
and all the values in the array for A[j + 1]
. Also you're not updating the sum variable. When you do sum = A[i] - A[i + 1]
because this operation only gives the variable sum a new value. What you want is sum+= value
, which means sum = sum + newValue (newValue = A[i] - A[i +1])
. This operation adds the new value to the old value stored in sum.
So what you need to do is add the two values and jump 2 indexes (i+=2
) so you don't do (for example) 3-4, 4-5, 5-6 etc. what you want is 3-4, 5-6, etc.
Try this:
public static void main(String[] args)
{
int[] A = {3, 4, 5, 6, 1, 2};
int total = 0;
int sum = 0;
for(int i = 0; i < A.length; i+=2)
{
sum +=(A[i] - A[i + 1]);
}
System.out.println(sum);
}
}
Upvotes: 1
Reputation: 445
I am not sure what are you stuck on exactly but looks like you are not adding the sum.
public static void main(String[] args)
{
int[] A = {3, 4, 5, 6, 1, 2};
int total = 0;
int sum = 0,i=0;
while(i<A.length){
sum+= (A[i] - A[i++]);
}
System.out.println(sum);
}
Upvotes: 0