How to create a Java method?
Hello, we are supposed to create a Java method that calculates the sum of all individual numbers up to an arbitrary number. We are supposed to code this task using while loops.
Can someone explain the task to me in words and give me an example, and then tell me how to get started?
thanks in advance
Well, what do you need? A variable that stores the previous sum. They are initialized with 0.
Then you need a loop that counts up to the desired number and adds the current number to the sum:
The method should now return the result:
Target number must be transferred to the method as a parameter. Your task is to google or look into the documents of your computer science teaching, how to declare a method with a parameter in Java 😉 Then you pack the above code and call it.
I guess it wasn’t the first time this question came up.
Maybe I didn’t look.
Ohso – nee, no copy & paste 😀 I can only type a bit fast…
Thought only because the answer was almost 1 minute after creating the question.
The task explained in simple words:
The program should ask for a number. For example, you enter a seven. Then the program should form the sum of all numbers up to 7.
So 1+2+3+4+5+6+7=28
Why you should do this with a while loop and not meaningfully with a for loop (or with the Gaussian cum formula), but I don't know. This is one of the peculiar special conditions that students are sometimes placed. Probably so that students learn to solve problems in different ways.
I used to make a few different variants: