w3resource

Java: Sum values of an array

Java Array: Exercise-2 with Solution

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

Java Code Editor:

Previous: Write a Java program to sort a numeric array and a string array.
Next: Write a Java program to print the following grid.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/array/java-array-exercise-2.php