Loops & Repetition in JavaScript

Loops & Repetition in JavaScript

We were only assigned one program to write this week, and it was dealing with what we’d learned about repetition control structures, typically called loops. We have the promise of more programs next week that focus more on this topic though.

The assignment was to create a program that allowed the user to enter an integer. The program would then add all the odd numbers between one and that integer inclusive and output the total to the user.

My first submission for peer review used the following function:

function sumOfOdds() {
 var input = parseInt(document.getElementById("input").value);
 var sumOfOdds = 0;
 for (var i = 1; i <= input; i += 2) {
 if (i % 2 != 0) {
 sumOfOdds += i;
 }
 }
 document.getElementById("sumOfOdds").innerHTML = "The sum of all odd numbers between 1 and " + 
 input.toLocaleString() + " is " + sumOfOdds.toLocaleString() + ".";
}

Fellow student, Sheldon, stated he liked my use of the not (!) operator to test for “not even” and he appreciated my liberal use of comments throughout the code. He also liked that I used the .toLocalString() method to output numbers with comma separators.

As I thought about what Sheldon said about testing for odd numbers, I realized that step was actually redundant. I was already incrementing my counter variable by two starting at one, which meant my values would always be odd. Looking at other students’ code, including Heather’s, I saw that most of them had simply used the correct increment to loop through only the odd numbers, so in my final submission I removed the extra test.

Another thing I realized from my first submission was the possibility of a user entering a negative integer, so I wanted to find a way to deal that possibility and give correct output. My final submission used an “if” statement and the Math.sign() method to determine if an input was negative. If the input was negative, the “if” statement would run a “for” loop that considered the negative state and correctly calculated an answer. If the input was not negative, an “else” statement would use the same “for” loop I used in my first submission. After some testing this all seemed to work perfectly.

Here was my final script:

function sumOfOdds() {
var input = parseInt(document.getElementById("input").value);
var sumOfOdds = 0;
if (Math.sign(input) == -1) { // Check to see if input is negative. If so, 
for (var n = 1; n >= input; n -= 2) { // start this loop to add the odd numbers.
sumOfOdds += n;
} 
} else { // Else if input is positive, run this loop.
for (var n = 1; n <= input; n += 2) {
 sumOfOdds += n;
}
}
document.getElementById("sumOfOdds").innerHTML = "The sum of all odd numbers between 1 and " + 
input.toLocaleString() + " inclusive is " + sumOfOdds.toLocaleString() + ".";
}

Leave a Reply

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