I was watching The Coding Train’s While Loop tutorial (lesson 6.1-see link below).
I had a really hard time digesting it and still don’t quite understand one thing. Why does it matter to reset x=0? I mean if you put “x=0;” before the While loop, shouldn’t it be useless?
- Java demands that local variables be initialized w/ some value before its 1st usage.
- Keyword
while
is seldom needed, if at all! Usefor
instead:
https://Processing.org/reference/for.html
Thanks. for is much simpler and easier to understand. Any idea when “while” is used in lieu of “for”?
- The rare occasions in which I see that a
while () {}
would be a better fit than afor () {}
block is when the conditional test to quit it isn’t based on some defined counter. - Something like when we request an input from a user, keep asking again while the input is still invalid.
- I’ve got a sketch that does just that here:
- Besides the inner block
while ((age = readByte("Enter your age:")) < 0);
it also has a variant calleddo {} while ()
as its outer block:
byte age;
do {
while ((age = readByte("Enter your age:")) < 0);
println("Your age is:", age);
} while (readBoolean("Again?"));
- There are other fitting situations that a
while () {}
block is better. - But for now I can only think about the 1 I’ve posted above.
Well, there’s an argument that while
is a simpler form of for
eg. these are equivalent
while (<condition>) { }
for ( ; <condition> ; ) { }
I have a related question to this same bit of code in this video:
float x = 0;
void setup(){
size(400,300);
}void draw(){
background(0);x=0;
while (x < width){
x=x+20;fill(101);
stroke (255);
ellipse(x,150,16,16);
}}
When it runs, it does this:
My question is, if x=0 at the start of the draw loop, why doesn’t the circle just draw at (20,150) and stop there?
Actually, through typing this out, I think I might have worked it out. Is it because x=0 isn’t inside the while loop? So it starts at 0, then the while loop fires until x > width?
OK, follow up question, why does it matter that x=0 is inside the draw loop when its already declared in the very first line at the top of the code? WIthout it inside the draw loop, it doesn’t draw a circle at all.
I think someone has maybe already answered this above but I’m really new to this (day 3) so I didn’t quite understand what they meant.
Thanks for your patience!
Any variable declared outside draw()
will retain the value it has between calls to draw (frames). So it’ll be 0 the first frame, and some value over width for every frame afterwards, because the loop keeps adding 20 to it until it is.
The x = 0
resets the value back to zero for the next frame, and so on.
Ahhh, ok cool, thank you!