Difference between revisions of "Summing arrays"
From CompSciWiki
(Changed to utilize CodeBlock template) |
|||
(11 intermediate revisions by 4 users not shown) | |||
Line 1: | Line 1: | ||
− | {{1010PrAD|ProblemName= | + | {{1010PrAD|ProblemName=Summing Arrays |
− | |Problem= | + | |Problem= |
+ | Let's start off with a small problem this week.<br> | ||
+ | Write a method that takes an array of integers are returns the sum. This might be useful for upcoming problems. | ||
+ | <br><br> | ||
− | + | |SideSectionTitle=More with Arrays | |
− | + | ||
− | + | ||
− | + | ||
− | |SideSectionTitle= | + | |
|SideSection= | |SideSection= | ||
− | [[Image: | + | [[Image:Wiki_method01.jpg|center]]<BR> |
− | <BR> | + | |
− | + | ||
− | + | ||
− | + | ||
|Solution= | |Solution= | ||
− | + | First, we are going to need our method header. We know that it takes an array of integers and returns an integer. | |
+ | {{CodeBlock | ||
+ | |Code= | ||
+ | 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. | ||
− | | | + | {{CodeBlock |
− | public | + | |Code= |
+ | 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. | ||
+ | |||
+ | |SolutionCode= | ||
+ | public static int sumArray(int[] myArray) | ||
+ | { | ||
+ | int sum; | ||
+ | |||
+ | sum = 0; | ||
+ | |||
+ | for(int counter = 0;counter < myArray.length();counter++) | ||
+ | { | ||
+ | sum += myArray[counter]; | ||
+ | } | ||
+ | |||
+ | return sum; | ||
+ | } | ||
}} | }} |
Latest revision as of 16:30, 4 December 2011
Back to the Program-A-Day homepage
ProblemLet's start off with a small problem this week. |
More with Arrays | |
---|---|---|
SolutionFirst, 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 |