Do while loop

Hi,

I am testing the do while loop as embedded.
I am not sure why the loop does not stop at 10 iterations it continues forever?

int x = 0;


void setup()
{
  Serial.begin(9600); 
}



void loop()
{


do {
  delay(50); 
  Serial.println(x); 
  x = x+1;   
} 
  while (x < 10);
  
}

You never reset x to zero in loop().

Its because you put the while() inside the loop(). It really counts up to 9, but then it ends and the void loop begins from the start. The while() loop begins once again, but this time x = 9 and the while() executes only once. Then the process repeats and while() executes only once... To solve the problem use the while() in the setup(). It executes only once. And if you want to work with numvers < 255, use byte instead on int.

Did you want to count to 9 and repeat the count again, or count to 9 and stop?

The loop() function runs forever.

When x=10 think about what will occur.

Then when x=11 etc.

This perfectly illustrates a danger with the do-while, which is also it's useful feature ... it always runs at least one time. If you had coded it more conventionally as a while, you would have no problem.

aarg:
Did you want to count to 9 and repeat the count again, or count to 9 and stop?

I want it to reach 9 and stop.
I don't want the put the do while in the setup

int x = 0;


void setup()
{
  Serial.begin(9600);
}



void loop()
{

  do {
    delay(50);
    Serial.println(x);
    x = x+1;   
  }
  while (x < 10);
 
  // Add this line...
  while(true);
}

while(x < 10)
{
delay(50);
Serial.println(x);
x = x+1;
}