# Values in Array

• 12-10-2011, 12:34 AM
jazob
Values in Array
I need to write a program that will look through a given array and find how many numbers can be expressed as the sum of 3 other numbers in the array.

Only 6 can be expressed as 3+2+1, so my program should print 1, but it prints 20.

Code:

```public class AddArray {   public static void main ( String[] args )   {     int [] array = {1,2,3,4,5,6};     int count = 0;         /* look through array four times*/     for (int i =0; i < array.length; i++)     {       for (int j = 0; j < array.length; j++)       {         for (int a = 0; a < array.length; a++)         {           for (int b = 0; b< array.length; b++)           {             if (array[i] == array[j] + array[a] + array[b])             {               count++;             }           }         }       }     }     System.out.println(count);   } }```
• 12-10-2011, 12:47 AM
Fubarable
Re: Values in Array
Your loops allow for duplicates, meaning it allows for 1 + 1 + 1. Try fiddling with your loop constants to eliminate this. Working out the logic on paper can help.
• 12-10-2011, 02:29 AM
jazob
Re: Values in Array
I've fixed that problem by changing int a and int b.
There's another duplicate problem also.
The counter will increase if the same number is expressed in more than one way.

I decided to set a, b, and j to the exit conditions whenever the counter increases by one so that I exit out of the three inner loops. That way, I can start from the outermost loop all over again.

Thanks for pushing me in the right direction.
Is there any other way to go around this problem?
Code:

```public class AddArray {   public static void main ( String[] args )   {     int [] array = {1,2,3,4,5,6,7,8,9,10};     int count = 0;     for (int i =0; i < array.length; i++)     {       for (int j = 0; j < array.length; j++)       {         for (int a = (j+1); a < array.length; a++)         {           for (int b = (a+1); b< array.length; b++)           {             if (array[i] == array[j] + array[a] + array[b])             {               count++;               b = array.length;               a= array.length;               j = array.length;             }           }         }       }     }     System.out.println(count);   } }```