While loop question

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?

2 Likes

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 a for () {} block is when the conditional test to quit it isn’t based on some defined counter. :robot:
  • 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: :sunglasses:
  • Besides the inner block while ((age = readByte("Enter your age:")) < 0); it also has a variant called do {} while () as its outer block: :dizzy_face:
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. :thinking:
  • But for now I can only think about the 1 I’ve posted above. :upside_down_face:
2 Likes

Well, there’s an argument that while is a simpler form of for :wink:

eg. these are equivalent

while (<condition>) { }
for ( ; <condition> ; ) { }
1 Like

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.

1 Like

Ahhh, ok cool, thank you!