Difference between revisions of "Summing arrays"

From CompSciWiki
Jump to: navigation, search
m (Minor typo fixes. Reworded a few parts of words to flow better.)
m (Fixed photo)
Line 8: Line 8:
 
|SideSectionTitle=More with Arrays
 
|SideSectionTitle=More with Arrays
 
|SideSection=
 
|SideSection=
[[Image:Wiki_method01.jpg|center]]
+
[[Image:Wiki_method01.jpg|center]]<BR>
<BR>
+
  
 
|Solution=
 
|Solution=

Revision as of 14:27, 9 April 2010

Back to the Program-A-Day homepage

Problem

Let's start off with a small problem this week.
Write a method that takes an array of integers are returns the sum. This might be useful for upcoming problems.

 

More with Arrays

Wiki method01.jpg

Solution

First, we are going to need our method header. We know that it takes an array of integers and returns an integer.

public static int sumArray(int[] myArray)
{
}

Only one variable is needed at the top of our method. This is the our running sum. This variable will be initialized to 0.

public static int sumArray(int[] myArray)
{
  int sum;
  sum = 0;
  return sum;
}

Now we need to iterate over all of our elements and add them up.

Code

Solution Code

Back to the Program-A-Day homepage