how do i wright a java program that adds the numbers between 1 and 1000...
When you have to solve a programming problem, I find it helpful to list out in words what you are trying to do;
- the answer is the sum of numbers 1 to 1000
- except 300 and 500
- somehow, either add the numbers individually
- just do not add 300 and 500
- or figure a loop that will increment the number to add to the answer
- figure out a way to check in the loop if 300 or 500 has come up and do not add them to the answer
So... possible program one:
Brute force answer = 1
answer = answer + 2
answer = answer + 3
.....
answer = answer + 299
// skip 300
answer = answer + 301
.....
answer = answer + 499
// skip 500
answer = answer + 501
... a thousand lines later ...
answer = answer + 1000
// It will work, but kind of dumb eh?
Possible solution two:
A Loop of some sort
for (every number between 1 and 1000) if it is a number I don't want, skip it (300 or 500)
otherwise, answer = answer + the current number
end of loop
// Perhaps an easier approach (at least easier to to type it in)
Possible solution three:
look up Karl Friedrich Gauss's answer- very cool
- no loops
- three steps
Just remember, if you can't write the problem down clearly in words, you don't understand the problem, and most likely, your solution will not work. Also, if your solution seems like a lot of work (like writing a thousand plus lines of code in the brute force approach) then there is probably a better way to solve it.
The Java language has many ways to loop, (while, do-while, for) and many conditional statements, (switch-case, if, if-else). Your job is to learn how to use these statements by putting them in some sort of order (a program) that will solve your problem. Feel free to ask how a particular statement works, but don't be discouraged if the answer is to look it up (we will help you with where to look it up). Just don't expect a solution to your homework, and if you do use a hint you find here, give credit where credit is due; like:
// solution based on help from the Java forum....