The Student Room Group

Javascript For Loop - Calculation

Having a problem with quite a lengthy java question. This is my first time doing java so I'm puzzled about where I should even start. I've googled java for loops but all of the examples I get are different to the example in the following question, so I don't know what bits are relative:

Write a for (syntax shown below) loop to calculate 1+2+3+4+5

for (initial expr.; test condition ; update expr.) {
JavaScript Statements go here.
}

b. Modify the test condition used above, so that the code can calculate 1+2+3+4+5+…+n, n is a variable for an integer number;

c. Modify the code above into a function called addN(n);

c. Create a Web page which contains a form with a text input field and a button.

The Text input field is used to get an input a integer number;
Name the button as Calculate;
Assign the value from input field to variable n;
Use branch condition statement if to implement the following within the function addN(n):
o if n<=20, display the calculation result.
o else, display the message: “Please input a number between 0 to 20!”
Use onclick event to call the function addN(n) in the body of the form


Help on any part of the above would be great.`
Reply 1
Have you got any ideas how to get started? It would be kinda pointless for us to just give you the solution. :smile:
Reply 2
I have no idea how to start, I'm not even sure what the question is asking. I'm not sure whether it's asking for one answer to 1+2+3+4+5 or for them to be added up sequentially, like a counting to 10 loop I've seen while searching.
Reply 3
The question asks "Write a for loop to calculate 1+2+3+4+5", doesn't seem too ambiguous?

This should be very straightforward (I assume you've been taught the basics of programming ie what a variable is etc). Google javascript for loop for some examples, etc.
Reply 4
Hint, define a variable outside the loop and use it as an accumulator.

Are you using Java or JavaScript btw? You mention both and they're *very* different languages.

Latest

Trending

Trending