Monday, January 20, 2025
HomeProgrammingJava Program That Print The Sum Of All The Items Of The...

Java Program That Print The Sum Of All The Items Of The Array

Here’s a simple Java program that calculates and prints the sum of all elements in an array:

public class ArraySum {
    public static void main(String[] args) {
        // Initialize an array with some values
        int[] array = {1, 2, 3, 4, 5};
        
        // Variable to store the sum
        int sum = 0;
        
        // Loop through each element of the array and add it to the sum
        for (int i = 0; i < array.length; i++) {
            sum += array[i];
        }
        
        // Print the sum of the array
        System.out.println("Sum of all elements in the array: " + sum);
    }
}

Explanation:

  1. Array Initialization:
    • We define an array array with integers {1, 2, 3, 4, 5}.
  2. Sum Calculation:
    • We initialize a variable sum to store the total sum of array elements.
    • We loop through the array using a for loop, and for each iteration, we add the current element (array[i]) to sum.
  3. Output:
    • After the loop completes, we print the value of sum, which holds the total sum of the array elements.
See also  What is Test Driven Development (TDD)?

Sample Output:

Sum of all elements in the array: 15

Alternative Using Enhanced For Loop (Java 5 and above):

You can also use the enhanced for loop (also known as the “for-each” loop) for more concise code:

public class ArraySum {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        int sum = 0;

        // Enhanced for loop (for-each loop)
        for (int num : array) {
            sum += num;
        }

        System.out.println("Sum of all elements in the array: " + sum);
    }
}

This version does the same thing but is more compact and readable. The enhanced for loop iterates directly over the elements in the array without using an index.

See also  How do I determine the size of my array in C?

Sample Output for Enhanced Loop Version:

Sum of all elements in the array: 15

Both approaches will give the same result, and you can use whichever one suits your coding style.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x