This task forces us to use the continue statement but I don't understand why?
Kingpvz
Level 31
What's the point of the continue statement?
Under discussion
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
Pinapleu
26 September 2024, 17:10
In what I've seen it helps make simpler code in some cases.
It could probably also be used for very small optimisations where parts of a long loop get skipped if they have no purpose anymore.
0
Dennis P. Nyemah
25 September 2024, 13:36
Alright so I think I've just figured out what exactly Kingpvz is asking.
Hence, I think Thomas is right about his statement "The reason to use the continue statement is probably to learn how to use it."
Because the task can also be solved like this:
for (int x = start; x < end; x++) {
if (x % multible == 0) {
sum = sum + x;
}
}
System.out.println(sum);
If start is evenly divisible by multible, add it to the sum variable. otherwise, do nothing and move to the next iteration of the loop.
Display the sum.
So the point is probably just to work with the continue statement in practice; having learned it in theory.
+2
Thomas
25 September 2024, 14:28
That's exactly how I understood the question, too. And without knowing the exact task conditions I thought of a more straight forward solution with less iterations and only one modulus operation like:
or
+1
Dennis P. Nyemah
25 September 2024, 11:05
In the task, you were told to use the continue statement because, you need to only display the sum of numbers in the range from start to end that are evenly divisible by the multiple variable.
That means if you don't use the continue statement, numbers in the range that are not evenly divisible by multiple will be added to the sum of numbers evenly divisible by multiple which is wrong to the task condition.
Inorder words, the continue statement will be used to skip all those numbers that are not evenly divisible by multilple.
If you can recall from the lesson, when the continue statement is executed(in a for loop), the body of the loop will be skipped, only statement 2 which is the increment variable will be executed inoder to get to the next number.
So you need to use the continue statement to skip all those numbers that are not evenly divisible by multible so that you can only add numbers that are evenly divisble by multible and display their sum.
0
Thomas
25 September 2024, 07:07
The reason to use the continue statement is probably to learn how to use it.
The point of the continue satetement: It is a way to control the program flow inside a loop. If you have one or two conditions a loop depends on, then it is mostly easy to fit that into the loops header. But sometimes that can be confusing or simply doesn't work.
0