Decrement problem

what is wrong with this code. the for statement is completely ignored and only 6 is printed.
can someone give the correct code?

int x;
void setup() {
Serial.begin(115200);
}
void loop() {
x=5;
for(int x=5;x<2;--x){
Serial.println(x);
delay(5000);
}
Serial.println(6);
delay(5000);
}
for(int x=5;x<2;--x){

This for loop will run while x is smaller than 2

Question : is x ever smaller than 2 ?

Your for loop in C++ follows this structure
for (initialization; condition; decrement) loopBodyExpression

The steps involved are:

  • Initialization is executed once before the loop starts, used to set up any variables.
  • Condition is checked before each iteration including the first one. If true, the loop continues; if false, it terminates.
  • The code inside the loop (loopBodyExpression ) is executed if the condition is true.
  • decrement is xecuted after the body on each iteration to modify the loop control variable(s) and the loop repeats the process until the condition evaluates to false.

So the question to ask yourself, if you don't enter at all the for loop could be:

Is the condition true or false at the first itération.

x is 5 after Initialization and the condition is x < 2 ➜ is that true or false ?

Nothing. From your description, it is doing exactly what it should do. The question is what did you want it to do?

If you want it to print 5, 4, 3... then you need to correct the criteria of the for-loop.

You might not also realise that you have 2 variables called x in your code. The variable declared on the first line and the variable declared inside the for-loop.

Once you have the for-loop running as you wanted, if you print the value of x after the for-loop you will see that it's value is still 5, and that is because the for-loop does not change that x variable, it changes only it's own x variable.

1 Like

presumably this is what you intended the code to do

output

for loop:
5
4
3

while loop:
5
4
3

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

    Serial.println ("for loop:");
    for (int x=5; x>2; --x)
        Serial.println(x);
    Serial.println ();

    Serial.println ("while loop:");
    int x = 5;
    while (x>2)  {
        Serial.println(x);
        --x;
    }
}

void loop() { }

At the start is one global variable called x.

The variable here called x and is used as an index pointer for the loop, is a totally different variable, to the x you defined as a global variable, but it has the same name. if you want to avoid this and use just the one global variable just use

for(x=5;x<2;--x){
1 Like

here is my corrected code Bob;

void setup() {
Serial.begin(115200);
}
void loop() {

for(int x=5;x>1;x--){
Serial.println(x);     //count down is true for values greater than 1 ie 5,4,3,2
delay(2000);
}
Serial.println(6);
delay(2000);
}

That looks better but does it do what you want ?

1 Like

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