Modify while loop to execute at-least once - java

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);

Related

There is no display of code for my program?

i'm not getting output for my java program?
package live;
public class ACTIVE
{
public static void main(String args[])
{
for(int i =0;i<0;i++)
{
if (i%2==0) {
continue;
}
System.out.println(i);
}
}
}
the output must be :
1
3
5
7
9
public static void main(String args[])
{
for(int i = 0; i < 10; i++)
{
if (i%2 == 0) {
continue;
}
System.out.println(i);
}
}
And the output is:
1
3
5
7
9
You set i to 0 and your for loop only runs if i<0, so change it to 10 and it should work.
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
if(i%2==0)
continue;
System.out.println(i);
}
}
It might help to specify exactly what the parts of a for loop are:
for(initialization; termination; increment)
The initialization expression sets up the initial conditions for the for loop.
The loop will stop when the termination expression evaluates to false.
The increment expression will execute once for every iteration of your loop.
So with that in mind, let's look at what your loop is actually doing:
for(int i = 1; i < 0; i++)
So your loop initializes by creating a variable named i and setting it to 1. Next, your loop says to terminate when i < 0 is false. But you just set i to be equal to 1, which is not less than zero! Therefore your termination condition is already false before you even start iterating through your loop, meaning that the loop never runs at all.
Based on your expected output, it seems like what you intended to write was:
for(int i = 1; i < 10; i++)
Notice that this will now terminate when i is greater or equal to 10.
Also, I'd recommend against this code for a couple of reasons:
if(i%2==0)
continue;
System.out.println(i);
It's generally bad practice to have if statements without using braces to delineate the code to be executed inside the if. Also, your logic is kind of "reversed", for lack of a better way of phrasing it. It would be (arguably) more intuitive to write:
if(i % 2 != 0) {
System.out.println(i);
}
That removes the need to continue, and slightly improves readability.
This code will not work because of loop condition fails
for(int i =0;i<0;i++)
or may be you forget to update condition to
for(int i=0; i<10; i++)
try this
package live;
public class ACTIVE {
public static void main(String args[])
{
for(int i=0; i<10; i++)
{
if(i%2==0)
continue;
System.out.println(i);
}
}
}
try this working fiddle
http://tpcg.io/KGl2Wr
i'm not getting output for my java program?
That is because your for-loop fails the given condition to run.
for(int i=0;i<0;i++)
//1) Initialize i as 0
//2) if i<0 is true, run statments within for-loop
At (2), the condition is false since 0 is not less than 0, hence your loop won't run. Try anything more than 0 for your loop to run ( e.g. i<1 )
Also, your continue statement can be avoided by doing:
for(int i=0;i<10;i++)
if(i%2 != 0)
System.out.println(i);
Let me keep it simple as possible without going deep into terminologies.
Let's take an example Ok?
Suppose I give you 10 bucks and I ask you to go and spend but you are allowed to spend only 0 bucks? Will you be able to spend any money? The answer is no right. Why is it so? It is because the condition doesn't match only, you won't be able to perform the task(here expenditure of money) right.
Similarly, in your loop, you have coded that :
for(int i=0;i<0;i++)
Now tell me look at this part of your code:
i=0 and i<0
Did you see what did you do wrong? You have told the program ok, I am setting the value of i to 0, you will have to run the loop till the part where i remains less than 0. But i can never be less than 0 because 0 is not less than 0. So your condition isn't satisfied at all and is not executed at all.
So what you need to do is set the condition as i<10 and your loop will work.
However, note that your loop can be made more effecient.
Hope it helps :D

Why this loop is endless

I am new to programming.
I was doing a homework, and I got a question about this code:
do {
int i=4;
} while (true);
Why is this loop endless?
It's one of the most basic things in programming - the while loop. The while loop keeps executing as long as its condition is truthy. So, since the condition in your code is true, it will run forever because there's nothing else to stop the loop.
Hopefully this will help you understand it:
var condition = true;
var i = 5;
do{
i--; // decrement the value of i
console.log('i is now', i);
if (i == 0)
condition = false;
} while (condition);
console.log('loop ended');
See it here: http://jsfiddle.net/9cr0yqp6/
you have not exit method. you never set the loop to false.
This is an infinite loop because you do not have a condition to exit the loop.
True will always be true so the loop continues to execute until your condition is false (which cannot happen).
This loop while infinitely create a local variable named i and then assign the value 4 to it.
This is Java, not JavaScript.
Loops continue to loop when the condition remains true.
Example of a loop that ends and an explanation why:
for(var i = 0; i < 5; i++) {
//do something
}
Each iteration i increases by 1 (due to i++), and once the condition (being i < 5) is no longer true, the loop breaks out and ends.
In your loop, true will always be true.
Perhaps to explain why the loop is endless, let's look at one that ends:
var i = 4;
do{
i = i + 1;
} while (i < 6);
This loop will iterate while it turns i to 5, then 6, and that will make the condition in the while statement false, which ends the loop.
If you have while (true) instead, the condition will never be false, and the loop never ends.
The "while" loop is endless because you set the condition to true.

Java Android For statement/loop parameters

Hello i've aquired some java code from an android sample project online and in the code there is a For statement/loop. The parameters for this For statement are displayed as (;;) rather than something like (int i = 0; i < string; i++). Can anyone explain exactly what this loop is doing by having the parameters as (;;)? i've tried researching online but can't find a thing!
thanks
for (;;) {
len = mSerial.read(rbuf);
rbuf[len] = 0;
if (len > 0) {
//do something
}
}
for (;;)
is an infinite for loop as there is no exit condition.
For loop syntax
for(initialization; Boolean_expression; update)
{
//body
}
initialization,Boolean_expression,update, body: all of them are optional. The for loop keep executing until Boolean_expression till it is not false. If Boolean_expression is missing then for loop will never terminate.
no initialisation, no exit condition, no increment.. it is a infinite loop?
It is an infinite loop. A for loop has 4 parts
for (initialisation; condition; increment/decrement) {
loop body
}
You may choose to omit any of these parts (although some compilers may complain about the lack of a loop body and others will omit the entire loop for performance).
It is perfectly feasible that you may already have a variable initialised, and may skip the initialisation within the loop:
int i = 0;
for ( ; i < 10; i++ ) {
// do something
}
It is also possible that you can choose to omit the incrementation, and do it elsewhere (be careful to include it inside the loop, otherwise this may lead to infinite loops unintentionally):
for ( int i = 0; i < 10; ) {
// do something
i++;
}
It is also possible to omit the conditional and include that elsewhere:
for ( int i = 0; ; i++ ) {
// do something
if (i == 9) {
break;
}
}
Or you can omit all of it entirely and make an infinite loop.
It is an infinite loop that does something when the if condition is satisfied. It can be used if you are waiting for an input from the user untill then it loops foreever.
When you declare for loop for (;;) .Every time loop will check the condition always it will return true so it goes in infinite loop.it is similar to while(true).if you want to break the loop then yo need to add break statement then it will come out from infinite loop.

Java: What is "for (;;)" [duplicate]

This question already has answers here:
How does a for loop work, specifically for(;;)?
(6 answers)
Closed 6 years ago.
Would any one please explain this instruction for me:
for (;;)
I have encountered several kinds of these mark (like in ajax code of facebook and in concurrent stuff of Java).
An infinite loop.
Each of the three parts of a for loop (for(x; y; z)) is optional.
So you can do this:
int i = 0;
for (; i < 20; ++i)
and it's perfectly valid, or
for (int i = 0; i < 20;) { ++i; }
or
for (int i = 0; ; ++i) { if (i < 20) { break; } }
and they're all valid.
You can also omit all three parts, with for(;;). Then you have a loop that:
does no initialization (the first part)
has no condition for stopping (the middle part)
does nothing after each iteration (the last part)
so basically an endless loop. It just does what it says in the loop body, again and again
It's an endless loop. For the specificion of the for statement, see here.
That's an infinite loop, similar to
while(true)
{
...
}
Its an infinite loop, seeing as the (non-existent) exit condition will never be false.
Any for loop without an exit condition will be infinite:
for (int x=0; ; x++) { }
Exactly the same as while (true), although a little less readable IMHO.
The syntax for a for loop is
for (init-stmt; condition; next-stmt) {
}
So it is simply a for loop with no initial statement, next statement or condition. The absence of the exiting condition makes it infinite.
That's indeed an infinite loop. But in Java you should really prefer while (true) over for (;;) since it's more readable (which you probably already realize). The compiler will optimize it anyway. In JavaScript there's no means of a compiler and every byte over HTTP counts, that's the reason why for (;;) is preferred. It saves a few characters (bytes).

what does "do" do here? (java)

I saw this bit of code on the interents somewhere. I'm wondering what the do is for.
public class LoopControl {
public static void main(String[] args) {
int count = 0;
do {
if (count % 2 == 0) {
for (int j = 0; j < count; j++) {
System.out.print(j+1);
if (j < count-1) {
System.out.print(", ");
}
}
System.out.println();
}
count++;
}
while (count <= 5);
}
}
By which I mean what exactly does do mean? What's its function? Any other information would be useful, too.
It is a do-while loop. So it will do everything in the following block while count is less than or equal to 5. The difference between this and a normal while loop is that the condition is evaluated at the end of the loop not the start. So the loop is guarenteed to execute at least once.
Sun tutorial on while and do-while.
Oh, and in this case it will print:
1, 2
1, 2, 3, 4
Edit: just so you know there will also be a new line at the start, but the formatting doesn't seem to let me show that.
It is similar to a while loop, with the only difference being that it is executed at least once.
Why? Because the while condition is only evaluated after the do block.
Why is it useful? Consider, for example, a game menu. First, you want to show the menu (the do block), and then, you want to keep showing the menu until someone chooses the exit option, which would be the while stop condition.
It's a while loop that gets executed at least once.
Edit: The while and do-while Statements
do { ... } while(CONDITION) ensures that the block inside do will be executed at least once even if the condition is not satisfied, on the other hand a while statment will never execute if the condition is not met
It goes with the while. do { ... } while() is a loop that has the conditon in the end.

Categories