0

I'm currently using this code to add all the numbers in an int array:

int sum = 0;
for (int i = 0; i < array.length; i++)
   {
      sum += array[i];
   }

int total = sum;  

For example if I had an array of numbers such as [1, 1, 2, 2, 3, 3, 1] and I only wanted to add all the 1's in the array, how would I go about doing so?

0

5 Answers 5

1

Just check if each array member is equal to 1 :

   int sum = 0;
   for (int i = 0; i < array.length; i++)
   {
      if (array[i]==1)
          sum += array[i];
   }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Your answer was the most direct and relevant out of the rest.
0

you need to compare that number with array index i;

int sum = 0;
int num = 0;// this number will compare with array index

 for (int i = 0; i < array.length; i++)
 {
      if (array[i]==num)
      sum += array[i];
 }
int total = sum;  

Comments

0

It really depends on how you choose those numbers. For example, if the number you chose has certain property(such as adding all 1,2,3 or adding all even number), you can use if statement to get the number. If the choice is depends on the certain property of index of the array, (add the No.1, No.2, No.3, No.5, No.8, No.13 ...) you can add another loop inside the "for" loop.

Comments

0

Inside loop filter it as

if (yourNumberToCompare==array[i]) {
    sum += array[i];
}

Where yourNumberToCompare is the number that you want to compare.

Final code will be

int sum = 0;
int yourNumberToCompare = 1; // this will be as per your choice
for (int i = 0; i < array.length; i++) {
    if (yourNumberToCompare==array[i]) {// this is the filter I was talking about
        sum += array[i];
    }
}

int total = sum;

Comments

0

Java 8 version:

    int[] integers = new int[]{1,2,3,4,5,6,7,8,9,1};

    int sum = Arrays.stream(integers).filter(x -> x == 1).sum();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.