Difference between revisions of "Passing Arrays using Methods"
From CompSciWiki
Line 2: | Line 2: | ||
Now you can do many different functions using an array. For example you can cacluate the average of an array, and print an array. Now let's look at how you could write a method to perform thoses tasks. Usuallly such methods will accept an array as an arguement. | Now you can do many different functions using an array. For example you can cacluate the average of an array, and print an array. Now let's look at how you could write a method to perform thoses tasks. Usuallly such methods will accept an array as an arguement. | ||
− | For example, the | + | For example, the below file, SumArray uses a for loop to sum the contents of an array: |
<pre> | <pre> |
Revision as of 15:16, 20 February 2007
Introduction
Now you can do many different functions using an array. For example you can cacluate the average of an array, and print an array. Now let's look at how you could write a method to perform thoses tasks. Usuallly such methods will accept an array as an arguement.
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