More Functions with Arrays

More Functions with Arrays

This week we were able to practice more with arrays. We wrote a program that utilized two different functions: one couting the even numbers in an array, and the other multiplying the array by another value. You can see my finished program here. My implementation of those two functions is below:


function countEvens(list) {
	var evensCount = 0;
	for (i = 0; i < list.length; i++) {
		if (list[i] % 2 == 0) {
			evensCount++;
		}
	}
	return evensCount;
}
function multiply(oldArray, multiplyBy) {
	var multiplesList = [];
	for (i = 0; i < oldArray.length; ++i) {
		multiplesList.push(oldArray[i] * multiplyBy);
	}
	return multiplesList;
}

I also added a couple of other functions, one that generated a random array and a random multiplier, and another that also returned the even numbers from the array instead of just counting them. Of course, I added a reset function to the form as well.

After posting my first draft for peer review, Bill commented that although my program worked fine, returning the list of even numbers was not a requirement of the assignement and the autograder may not grade it well. I considered what he said, and it made me realize perhaps doing more than asked isn’t always a good thing, especially when it overcomplicates the solution to a simple problem. So, although I wanted to keep the ability to also return the list of even numbers, in my final program I decided to seperate that ability into it’s own function instead of including it with the counting function. This simplified my required functions and did indeed allow the autograder to work as expected.

I noticed on this assignment that some students were misunderstanding the instructions and were returning only a list and not a count of the evens. I hope that the submission of my code with the evens list didn’t confuse others. I commented on a few other students’ code, including Seth’s, Greg’s, and Andrew’s. Andrew was working to implement the multiplication function and I suggested he do something similiar to my function, which was to create a loop that multiplied each value from the original list array, then used the array “push” method to place them in a new array which is then returned to the function call.

Overall, this was a great week with a fun assignment. I’m looking forward to the final exam this coming week.

Array Practice #2

Leave a Reply

Your email address will not be published. Required fields are marked *