-3

The program usually displays something like 1+3+5+=9 but i want to get rid of the + after 5. Please help me with this issue that I have right now at the moment.

var userNum = prompt("Pick a number and every odd number between 1 and that 
number will be added");

var  increase = 0;

 var totalSum = 0;

 var expression = "+";

document.write("the sum of the odd numbers are:");
// while the increase is less than the userNum , the increase will 
increase by one

while(increase < userNum){
  increase++
  // if the increase is odd , it will be added to the totalSum
  if(increase % 2 === 0){

  } else {
    document.write(increase+ expression)
    totalSum = totalSum + increase
  }
}

document.write( 0+ "=" + totalSum);
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
  • It would generally be easier to either a) store the expression in memory until you're done, then write it out, at which point you can truncate the extra character with String.slice; or b) change your logic to avoid printing the plus sign if don't want it. It might be counter-intuitive, but consider maybe writing out the expression at the start of the loop any time it's not the first iteration. – Mic May 09 '17 at 21:26
  • A couple other critiques, you don't need to iterate over every number and check whether it's odd or even. If you initialize "increase" to an odd number (maybe 1, for example) and then add 2 to it each time you loop, it will always be the next odd number. It's also often easier to work out the logic if you increment the variable at the end of the loop rather than start - though that's more a preference. – Mic May 09 '17 at 21:29

6 Answers6

2

You could put the + sign in front, and on the first iteration, don't add it:

var userNum = prompt("Pick a number and every odd number between 1 and that number will be added");

var increase = 1,
    totalSum = 0,
    expression = "+",
    str = "The sum of the odd numbers is: ";

while(increase < userNum) {
    if(increase !== 1) { str += expression; }
    str += increase;
    totalSum += increase;
    increase += 2;
}

document.write( str + "=" + totalSum );
blex
  • 24,941
  • 5
  • 39
  • 72
1

Instead of creating the output while iterating, put your numbers into an array and simply .join("+") (MDN) the final array to create the string 1+3+5 for output at the end.

I leave the implementation for you as an exercise.

Filburt
  • 17,626
  • 12
  • 64
  • 115
0

Try checking for the last iteration of the while loop like- (you can replace your while loop with the below one)

while(increase < userNum){
  increase++
  if(increase % 2 !== 0){
    if(increase === userNum){
      document.write(increase)
    }else{
      document.write(increase+ expression)
      totalSum = totalSum + increase
    }
  }
}

Hope this helps.

optimistanoop
  • 912
  • 1
  • 11
  • 14
0

add values to array and join with + sign.

HTML:

<div class="sum">
</div>

JS:

 var userNum=10;

var  increase = 0;

 var totalSum = 0;

 var expression = "+";

   $('.sum').text("the sum of the odd numbers are:");
  // while the increase is less than the userNum , the increase will 
   //increase by one
   var txt=[];
   while(increase < userNum){
  increase++
   // if the increase is odd , it will be added to the totalSum
    if(increase % 2 === 0){}
    else{
         txt.push(increase);
            totalSum = totalSum + increase
    }    
}
$(".sum").text(txt.join("+") + "=" + totalSum);

https://jsfiddle.net/u5o9qb0c/

Liquidchrome
  • 894
  • 5
  • 10
0

First and foremost, don't use document.write(). It has very limited use cases and more often than not will overwrite your existing document. Instead, set up an empty HTML element to use as an "output" area and then just write into that area.

Next, you get the extra + symbol because you are writing:

document.write(increase + expression);

and expression is hard-coded to the + symbol.

You'll need to only add that when another operand is added.

It should be like this:

/* 
   Place all of this code in "script" tags and place those tags
   just before the closing body tag (</body>) so that this code won't run
   until all of the HTML is parsed
*/

// Get a reference to the output element
var output = document.getElementById("output");

var endNum = prompt("Pick a number and every odd number between 1 and that number will be added");

// Since we know you want to start at 1, initialze the variable to 1
var increase = 1;
var totalSum = 0;

// This will hold the result that will be injected just once into the document
var result = "";

// while the increase is less than the userNum , the increase will increase by one

while(increase < endNum){
  // Just check to see if we've already started writing the result
  // and prepend the + sign if so.
  if(result !== ""){
    result += "+";
  }
  result += increase;
  totalSum += increase;

  // Just increment by 2 to stay with odd numbers
  increase += 2;
}

output.innerHTML += result + "=" + totalSum;
<div id="output">
  <h1>The sum of the odd numbers are:</h1>
</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
-1

What you're doing could be a lot more concise. See below.

Changed this increase variable to initialize to one, because that's always your first value according to the prompt.

Starting the expression as the leading text, because a) I want this printed before anything else, and b) I don't want the plus sign on the first iteration

Regarding the expression assignment in the loop, it's unnecessary to assign this every iteration as I have, it's more concise to just assign it than to check if I need to do it every time.

I move the increment of increase to later in the loop so that the value that gets printed is the what it is at the start of the loop. It's a matter of preference, but I would have had to initialize it to -1 if I wanted this to work with it incrementing before the document.write, which I don't like from the standpoint of conveying clear intent.

I also got rid of the semicolons for no reason at all other than that they weren't necessary. (Addendum: In the context of this discussion, I'm not prescribing making this change. It's my code style, but adding semicolons between the statements would have no relevant impact on the code snippet.)

  var userNum = prompt("Pick a number and every odd number between 1 and that number will be added")
  var  increase = 1 
  var totalSum = 0
  var expression = 'the sum of the odd numbers are:'
  
  while (increase <= userNum) {
    document.write(expression + increase)
    totalSum += increase
    increase += 2
    expression = '+'
  }

 document.write("=" + totalSum)
Mic
  • 3,810
  • 1
  • 13
  • 16
  • Semicolons are how the JavaScript runtime knows where a statement ends. Although JavaScript has automatic semicolon insertion, it is not always reliable. And for that reason, developers should never rely on it. You should always include them in your code. – Scott Marcus May 10 '17 at 11:06
  • That's not really the case, you're repeating FUD that gets drilled into anyone. 1) Automatic insertion is as reliable or more so than manual insertion. 2) Semi-colons are not statement terminators, they're separators. You could as easily put them at the beginning of each new statement. – Mic May 10 '17 at 11:35
  • Further info - http://inimino.org/~inimino/blog/javascript_semicolons and https://youtu.be/gsfbh17Ax9I – Mic May 10 '17 at 11:36
  • @ScottMarcus Guys you're not seriously starting to DV each others valid answers arguing over semicolons? – Filburt May 10 '17 at 12:06
  • @Filburt This isn't going to be a back and forth. I don't have time for that. I only responded because ScottMarcus made a comment that is more religion than fact, and I wanted to make a correction for the next person that comes along and reads the thread. – Mic May 10 '17 at 12:17
  • I do feel compelled to also "correct" the record, because the advice to not worry about manually inserting semicolons is very bad advice, plain and simple. That advice is very much in the minority and tends to come from people who don't work collaboratively on code or in environments where coding standards have been established. When it comes to best-practices, following a behavior that "sometimes" can lead to bugs vs. a behavior that eliminates those kinds of bugs entirely, the choice is clear. – Scott Marcus May 10 '17 at 12:37
  • This page not only has the overwhelming opinion of fellow SO members, but it you look through the myriad of links supplied as further evidence, you'll understand that this is much more than just "religion" or preference. Leaving the semicolons out can cause bugs. http://stackoverflow.com/questions/444080/do-you-recommend-using-semicolons-after-every-statement-in-javascript Additionally, any JSLinter will flag the omission of the semicolons. There's a reason for that. – Scott Marcus May 10 '17 at 12:39
  • It's just more FUD, it's not based in fact. It's true that there are edge cases (less than a half-dozen and I know all of them) where a semicolon is necessary. As in the link there, a closure, on a line by itself, without an assignment is one of them. I would neither count 74 upvotes of a statement with no backing evidence as "the overwhelming opinion", nor would I say that the myriad of links support it, unless you cherry pick for confirmation bias. If we're going to bring opinionated tools into it, https://standardjs.com/ prescribes removal of unwanted semicolons. Stop spreading false info. – Mic May 10 '17 at 12:59
  • @Mic Ok Mic. Good luck to you. – Scott Marcus May 10 '17 at 13:34