Java Array Sum arraySum(int[] intArray, short flag)

Here you can find the source of arraySum(int[] intArray, short flag)

Description

Returns the sum of the values of all integer elements in an integer array

License

Open Source License

Parameter

Parameter Description
intArray the integers to calculate the sum of
flag this flag is meant to check if all elements in the array must be positive (0), negative(1), or it doesn't matter (anything else)

Exception

Parameter Description
IllegalArgumentException if precondition is violated

Return

sum(i = 0; intArray.has(i); intArray[i])

Declaration

public static int arraySum(int[] intArray, short flag) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*  w w w .  j a  v a2 s.c  o  m*/
     * Returns the sum of the values of all integer elements in an integer array
     *
     * @param intArray the integers to calculate the sum of
     * @param flag this flag is meant to check if all elements in the array must
     * be positive (0), negative(1), or it doesn't matter (anything else)
     * @pre
     * {@code (flag != 0 && flag != 1) || (flag == 0 && (\forall i; intArray.has(i); i >= 0)) || (flag == 1 && (\forall i; intArray.has(i); i <= 0))}
     * @throws IllegalArgumentException if precondition is violated
     * @return {@code sum(i = 0; intArray.has(i); intArray[i]) }
     */
    public static int arraySum(int[] intArray, short flag) {
        int r = 0;
        for (int i : intArray) { //check flag
            if (flag == 0 && i < 0) { //
                throw new IllegalArgumentException(
                        "all integers in array must be positive");
            } else if (flag == 1 && i > 0) { //
                throw new IllegalArgumentException(
                        "all integers in array must be negative");
            }
            r += i;
        }
        return r;
    }
}

Related

  1. ArrayCeilSum(float[] a)
  2. arraySum(double[] a)
  3. arraySum(double[] arr)
  4. arraySum(final double input[])
  5. ArraySum(float[] a)
  6. getSum(int[] array)
  7. getSum(int[] array)
  8. sum( int[] a)
  9. sum(byte... bytes)