英文:
How can I use a while loop in java to find the sum of all numbers between 0 and a given integer?
问题
I'm happy to join the community. I have no prior experience in coding, and I am currently taking my very first steps into Java programming. Can someone please help me understand and solve the problem in the labs about loops in Java? Please find attached the screenshots of the labs. Thank you for helping.
Loops in Java and here.
What is the code for a while loop to get the sum of all numbers between 0 and "end" (exclusive)?
英文:
I'am happy to join the community. I have no prior experience to coding and I am currently experiencing my very first steps into java programming. Can someone please help me understand and solve the problem in the labs about the loop in java. Please find attached the screenshots of the labs.
Thank you for helping[Loops in java](https://i.stack.imgur.com/7FkEL.png)
What is the code for a while loop to get the sum of all numbers between 0 and end (exclusive)
答案1
得分: -1
请注意,你的_while循环_被注释掉了。
这是关于_while_和_do-while_循环的Java教程。
while和do-while语句(Java™教程 > 学习Java语言 > 语言基础)。
在Java中,要创建一个while循环,你可以使用以下结构。
while (i < end) {
}
要计算从_i_到不包括_end_的值的总和,你可以使用以下代码。
sum = sum + i;
i = i + 1;
要返回_sum_的值,你可以使用以下代码
return sum;
总之,_whileExample_方法的完整代码如下。
int whileExample(int end) {
int sum = 0;
int i = 0;
while (i < end) {
sum = sum + i;
i = i + 1;
}
return sum;
}
英文:
Note that your while-loop is commented-out.
Here is a Java tutorial on while and do-while loops.
The while and do-while Statements (The Java™ Tutorials > Learning the Java Language > Language Basics).
In Java, to create a while-loop, you use the following structure.
while (i < end) {
}
To derive a sum of values, from i to an exclusive end, you can use the following.
sum = sum + i;
i = i + 1;
To return the sum value, you use
return sum;
All together the code for the whileExample method would be as follows.
int whileExample(int end) {
int sum = 0;
int i = 0;
while (i < end) {
sum = sum + i;
i = i + 1;
}
return sum;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论