ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Sum the contents of an Array in Java

Updated on August 28, 2011

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;
    }

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article