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

  • Fun Facts about your Washing Machine
    25

    Churning round and round in the basement, the washing machine usually spends its' useful life as an unappreciated member of the appliance family...

  • Data Hiding in Java
    12

    Data Hiding is an aspect of Object Oriented Programming (OOP) that allows developers to protect private data and hide implementation details. In this tutorial we examine basic data hiding techniques in Java.

  • Introduction to Windows Notepad
    5

    A useful text editor is an essential component of any personal computer. Every day we need to make notes, compose documents, and record vital pieces of information. We depend on our text editor. Microsoft provided...


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