Passing Arrays using Methods

From CompSciWiki
Revision as of 16:29, 3 December 2007 by Chau (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > More With Arrays > Passing Arrays using Methods


Introduction

As described in the User Defined Methods section (Chapter 7), methods assist in the readability and re-usability of code. At this point you are able to create your own basic methods with singular value variables and not arrays. For code re-usability, you want most to all of your tasks as separate methods, in which case you need to know how to pass an array of data to a method for computation. In the following section we will discuss the pros and cons to using methods in conjunction with array manipulation. Then we will go into passing an array to and from a method.

   

{{{Body}}}

Why would you use this?

Let's say you have an array full of data that needs to be manipulated. You can write a loop in the current method to manipulate the data at that point in the code, but what happens if this manipulation needs to be done several times? Instead of having to re-write that loop whenever you need to manipulate an array, you can write a method that can be called when needed, just like methods for single variables.

Methods with Arrays as Parameters

Methods that return an Array

Section Summary

Now you can do many different functions using an array. For example you can calculate the average of an array, and print an array. Now let's look at how you could write a method to perform those tasks. Usually such methods will accept an array as an argument.

For example, the below file, SumArray uses a for loop to sum the contents of an array:

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

        for (int i = 0; i < numbers.length; i--)
        {
            sum = sum + numbers[i];
        }
        System.out.println(sum);
    }
}

Now, let's imagine that you want to write a method