Search code examples
javaarraysinteger

Sum up integer values of an int[]-parameter and return the result


How can I sum up the integer values of an int[]-parameter and return the result

Sample1: [1,2,3] must return 6
Sample2: [-7,7,3] must return 3
Sample3: [] must return 0
public static int calculateSum(int[] values) {
        int[] array = {10, 20, 30, 40};
        return Integer.MIN_VALUE;
    }
}

Solution

  • Try this

        public static int calculateSum(int[] values) {
            int result = 0;
    
            for(int i=0; i<values.length; i++){
                result += values[i];
            }
    
            return result;
        }
    }