2

I'm trying to create a while loop that outputs a list of values, adds them together, and outputs a total with an "=" sign at the end I.e., if the User enters the numbers 5 and 12, the output would show up like this: 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 = total

This is how my 'while' loop looks right now:

while(enteredNum1 <= enteredNum2){
    total += enteredNum1;
    document.write(enteredNum1 + " + ");
    enteredNum1++;
}

document.write("= " + total); 

I know it will always append the " + ", but can anyone point me in the right direction for having the last value show "=" instead of the "+" again?

1
  • you could write the plus separate to enteredNum1 and check if the loop will run again, if it will write the + otherwise carry on Commented Oct 28, 2014 at 16:10

4 Answers 4

5

Alternative;

var numbers = [];
while(enteredNum1 <= enteredNum2){
    total += enteredNum1;
    numbers.push(enteredNum1++);
}

document.write(numbers.join(" + ") + " = " + total); 
Sign up to request clarification or add additional context in comments.

Comments

1

Proper way:

list = [];
total = 0;
enteredNum1 = parseInt(enteredNum1); // parseInt only if enteredNum1 can be a string
while(enteredNum1 <= enteredNum2) {
    total += enteredNum1;
    list.push(enteredNum1);
    enteredNum1++;
}

document.write(list.join(" + ") + " = " + total); 

Comments

0

Any easy way would be an if statement checking if the loop will continue:

while(enteredNum1 <= enteredNum2) {
    total += enteredNum1;
    if (enteredNum1 + 1 <= enteredNum2) {
        document.write(enteredNum1 + " + ");
    } else {
        document.write(enteredNum1);
    }

    enteredNum1++;
}

document.write(" = " + total);

Alternatively, saving the output as a string and taking the "+" off using substring would work as well

3 Comments

Thank you, SuckerForMayhem! Never considered using an if/else within the while loop!
Consider using an array instead of calling many times document.write and increase complexity with if/else. See below.
@KyleK I agree, using an array and join is better, this was just a simple alteration
0

This should work:

total += enteredNum1;
document.write(enteredNum1);
enteredNum1++;

while(enteredNum1 <= enteredNum2){
    total += enteredNum1;
    document.write(" + " + enteredNum1);
    enteredNum1++;
}

document.write("= " + total); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.