1

I have a problem with a for loop, and Serial.print("Its Working") does not appear. Seems simple, I've done it before, now for whatever reason, its not working anymore

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:

  for (int x = 0; x > 10; x++) {

    Serial.println("Its Working");
    delay(1000);
  }
}

1 Answer 1

6

The problem is:

for (int x = 0; x > 10; x++) {

That can be rewritten, in pseudo code, as:

  • X is zero
  • While X is greater than 10:
    • Increment X

You see the problem? X is zero. It's not greater than 10, so it never increments.

I assume you actually wanted:

for (int x = 0; x < 10; x++) {

Also be aware that your for loop will be run over and over again, so you will never see it finish. You should add

Serial.println("Loop done");

at the end so you know it's finished.

4
  • Essentially, the for loop never starts as the first time it checks the condition, its already false, right?
    – Coder9390
    Commented May 3, 2021 at 13:26
  • @Coder9390 That is correct.
    – Majenko
    Commented May 3, 2021 at 13:29
  • @Coder9390: You can see that for yourself by single-stepping your code with a debugger. You'll see execution skip over the loop without ever entering the loop body. That's your hint that you accidentally wrote a loop condition that's false on the first check. Remember that a for loop is basically the same as part1; / while(part2){ ...; part3; }, so like a while loop, the condition is checked before entering the loop for the first time. Commented May 4, 2021 at 4:27
  • @Coder9390: Using a debugger is essential for low-level stuff where alternatives like sprinkling debug-print statements in your code aren't easy, or to help catch brain-farts where something you're assuming you got right was actually the problem. Commented May 4, 2021 at 4:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.