antonlab
antonlab

Reputation: 343

How to add a certain number in an array of numbers?

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?

Upvotes: 0

Views: 2038

Answers (5)

s.d
s.d

Reputation: 29436

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();

Upvotes: 0

Fahim Parkar
Fahim Parkar

Reputation: 31631

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;

Upvotes: 0

Victor Cooper
Victor Cooper

Reputation: 73

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.

Upvotes: 0

MilapTank
MilapTank

Reputation: 10076

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;  

Upvotes: 0

Eran
Eran

Reputation: 393781

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];
   }

Upvotes: 1

Related Questions