w3resource

Java: Sum values of an array


2. Sum all values in an array

Write a Java program to sum values of an array.

Pictorial Presentation:

Java Array Exercises:  Sum values of an array


Sample Solution:

Java Code:

// Define a class named Exercise2.
public class Exercise2 {
    // The main method where the program execution starts.
    public static void main(String[] args) {      
        // Declare and initialize an integer array.
        int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        
        // Declare and initialize a variable to store the sum.
        int sum = 0;
        
        // Iterate over each element of the array using an enhanced for loop.
        for (int i : my_array)
            // Add each element to the sum.
            sum += i;
        
        // Print the sum of the array elements.
        System.out.println("The sum is " + sum);
    }
}

Sample Output:

The sum is 55  

Flowchart:

Flowchart: Java exercises: Sum values of an array


For more Practice: Solve these Related Problems:

  • Write a Java program to find the sum of alternate elements in an array.
  • Write a Java program to find the sum of all even and odd numbers separately in an integer array.
  • Write a Java program to find the sum of digits of each element in an array.
  • Write a Java program to calculate the sum of an array using recursion.

Go to:


PREV : Sort numeric and string arrays.
NEXT : Print a 10x10 grid of dashes.

Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.