doing some exam revision. One question is, Modifiy code to so that the loop will execute at-least once.
My Code :
int x = 0;
while (x < 10) {
if (x % 2 != 0) {
System.out.println(x);
}
x++;
}
Now i know while will loop while the condition is true, i know i cannot remove the x++ as this will give me infinite zeros. i think i would just remove the if statement and the brace related to it.
would you agree?
int x = 0;
while (x < 10) {
System.out.println(x);
x++;
}
Although this specific loop actually executes at least once even unchanged, that is not a property of a while-loop.
If the condition in the while-loop is not met, the loop never executes.
A do-while loop works almost the same way, except the condition is evaluated after execution of the loop, hence, the loop always executes at least once:
void Foo(bool someCondition)
{
while (someCondition)
{
// code here is never executed if someCondition is FALSE
}
}
on the other hand:
void Foo(bool someCondition)
{
do
{
// code here is executed whatever the value of someCondition
}
while (someCondition) // but the loop is only executed *again* if someCondition is TRUE
}
I would not agree, that would change the fundamental purpose of the loop (to emit every other number to stdout).
Look into converting to the do/while loop.
Whilst your solution has technically answered the question, I don't think it's what they were looking for (which isn't really your fault, and makes it a badly-worded question in my opinion). Given it's an exam question, I think what they're after here is a do while
loop.
It works the same as a while
loop except that the while
condition is checked at the end of the loop - which means that it will always execute at least once.
Example:
while(condition){
foo();
}
Here, condition
is checked first, and then if condition
is true
, the loop is executed, and foo()
is called.
Whereas here:
do{
foo();
}while(condition)
the loop is executed once, foo()
is called, and then condition
is checked to know whether to execute the loop again.
More:
For further reading you might want to check out this or this tutorial on while
, do while
and for
loops.
int x = 0;
while (x <10){
System.out.println(x);
x++;
}
Will work
EDIT: i think the others comments are rights too, the do/while loop will force one execution of the code
var x = 0;
do {
if (x % 2 != 0) System.out.println(x);
x++;
} while (x < 10);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.