Having some trouble incrementing counters So, I have some simple code here. I'll just try and explain what I am trying to have my code do here. 

I am trying to rotate my stepper motor by half a turn, and then move it back and forth by 200 steps or so.

The problem I have is in my loop function, where I have a variable called ctr. I am trying to increment this ctr when I execute an if statement. The ctr increments inside the if statement and I can see the result when I do Serial.println as it changes to 1. However, when I Serial.println(ctr) right below the if statement, it prints out as 0 even after the previous print statement prints out 1.

Why is this happening? I am a C/C++ noob, so is there something I am missing about variable scoping or pointers?

void loop()
{
    stepper1.run();
    int ctr = 0; //counter value to store how many times the back and forth motion has occured
    if(stepper1.currentPosition() == 1024){
      backMotion(stepper1.currentPosition());
      ctr++;
      Serial.println(ctr);
    }
    Serial.println(ctr);
    if(stepper1.currentPosition() == 824 &amp;&amp; ctr &gt; 0){
      forthMotion(stepper1.currentPosition());
    }
}  

void backMotion(int value){
    int current = value;
    int back_distance = current - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

void forthMotion(int value) {
  int current = value;
  int forth_distance = current+200;
  stepper1.moveTo(forth_distance);
}
Make CTR static or place it in the global scope. As it stands you set it to 0 every time you go through loop.

The line:

int ctr = 0;


literally means "Create a new variable on the stack called 'ctr' and give it the value 0", and that happens every time loop() is executed.

Instead making it static will change it so that it only happens the first time loop() is executed so it retains its value across successive executions of loop().

static int ctr = 0;