Sum the contents of an Array in Java

Introduction

This program illustrates a technique for summing the contents of an array using Java. Java, unlike C++, manages arrays to the extent that the size/length of the object can be determined at run time.

// This method demonstrates how to sum an array of integers
// Add this method to a class.
// The array is passed into the method as an argument.
// Unlike C++, java provides a method for the array type that
//  returns the size / length of the array. We call this method
//  at runtime to determine how many elements are in the array,
//  then that value becomes the upper bound for our loop.
//
// The method returns the result of the calculation.

 //  Part 2a
    public static int sumArray(int myArray[]) {
        int i, sum = 0;
        // Write a loop to step through the array and sum the elements
        for (i = 0; i < myArray.length; i++) {
            sum = sum + myArray[i];
        }
        // Use a return statement to send back the calculated reault
        return sum;
    }

// This method demonstrates how to sum an array of integers
// Add this method to a class.
// The array is passed into the method as an argument.
// Unlike C++, java provides a method for the array type that
//  returns the size / length of the array. We call this method
//  at runtime to determine how many elements are in the array,
//  then that value becomes the upper bound for our loop.
//
// The method returns the result of the calculation.

 //  Part 2a
    public static int sumArray(int myArray[]) {
        int i, sum = 0;
        // Write a loop to step through the array and sum the elements
        for (i = 0; i < myArray.length; i++) {
            sum = sum + myArray[i];
        }
        // Use a return statement to send back the calculated reault
        return sum;
    }

More by this Author


Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working