Switch-Case Statement & Printing to Serial Monitor

So I'm new to Arduino and experimenting with switch-case statements. I want to have a basic for loop count 3 times and print a message to the monitor. When I run the code nothing shows up on the screen. Any ideas about what I am doing wrong?

int x;

void setup() {

Serial.begin(9600);

for(int x = 0; x < 0; x++);{
  
switch (x) {
  case 1:
    Serial.println("My name is Bob");
    break;
  case 2:
    Serial.println("Sike");
    break;
  case 3:
    Serial.println("No it's not");
    break;
  default:
    break;
    }
  }
}

void loop() {
}

Oops

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

The last semicolon is the only code in the for loop code block. Delete it

I did that but still nothing prints to the monitor

Please post your revised code

int x;

void setup() {

Serial.begin(9600);

for(int x = 0; x < 0; x++){
  
switch (x) {
  case 1:
    Serial.println("My name is Bob");
    break;
  case 2:
    Serial.println("Sike");
    break;
  case 3:
    Serial.println("No it's not");
    break;
  default:
    break;
    }
  }
}

void loop() {
}
x < 0;

Will x ever be less than 0 in the for loop ?

Yeah I realized that x would never be less than zero and adjusted it but now it only prints the first string of text.

    Serial.println("My name is Bob");
    break;

Shouldn't it theoretically keep going and print all 3 because the for loop will keep incrementing?

Once again, post your revised sketch
It would be interesting for you if you printed the value of x inside the for loop

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

  for (byte x = 0; x < 4; x++) {
    switch (x) {
      case 1:
        Serial.println("My name is Bob");
        break;
      case 2:
        Serial.println("Sike");
        break;
      case 3:
        Serial.println("No it's not");
        break;
      default:
        break;
    }
  }
}

void loop() {}
1 Like

Ah I figured it out now thx

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.