In one of my first software development interviews, I was asked to write a simple script that sums the integer elements in an array. As part of my professional development, I would like to share the code I’m writing for two reasons. One, because it might help other aspiring developers to hone their craft. Secondly, because it helps me better understand what is happening in the code. Generally speaking, if you are able to explain your code satisfactorily, you have a better understanding of the language. There are may ways to do this but here is what I did in the interview. I was given the choice to write the solution in any language and even pseudo-code. I chose javascript because that was the language I had been learning most recently.
For this example, I used http://codecademy.com ‘s awesome scratch pad. If you haven’t checked that site out and you are new to coding, I highly recommend it!
Explanation of the function:
Step 1: If your going to sum the elements in an array, it helps to have an array to sum! The elements within can be as long and varied as you like. I chose 1,2,3,4 for simplicity.
Step 2: I declare a function called ‘sumArray’ and give it one parameter. Obviously, the function is meant to accept an array as a parameter.
Step 3: Inside the function (always a good practice to declare variables inside a function when they are specific to that function) I declare my ‘accumulator’ –> ‘result’ and set it to ‘0’. on the next line I write a basic counter that sets how many times the loop will run before stopping. The second part of the stuff in the parantheses stops the loop when the end of the array is reached. Remember, we passed in ‘myArray’ and it is now represented by ‘number’. We make it zero , so that it has an initial value.
Step 4: Through each step of the loop the sum of result (which is 0 initially) is added to each element of the array by it’s index (input[i]). Arrays are zero indexed, so each element is referenced by starting at i=0 and increasing incrementally, i++, until it reaches the end of the loop.
Step 5: Outside of loop (very important in this case), we return the new value of result.
Step 6: Call the function on ‘myArray’.
Step 7: Bask in the glory of your awesomeness…. 🙂
var myArray = [1,2,3,4];
function sumArray(input) {
var result = 0;
for(i = 0; i < input.length; i++) {
result = result + input[i];
}
return result;
}
sumArray(myArray);