Search code examples
c++for-loopc++17mql4mql5

How to get the last index in a for loop


i am coding in a language similar to c++ known as mql5.(for mt5 trading platform) they have many similarities... i have a for loop as shown below:

void OnTick()  // this functon basically executes the code after every price change.
{
   for (int i = 0; i<5; i++)  //the for loop function
    {
     Print(i);  //this prints the loop
    }
}

the result of the code above with each price change overtime is:

13:27:18.706    0
13:27:18.706    1
13:27:18.706    2
13:27:18.706    3
13:27:18.706    4

13:27:18.900    0
13:27:18.900    1
13:27:18.900    2
13:27:18.900    3
13:27:18.900    4

question is, how do i access the last element in the index of the for loop and get it to print 4th index each time price changes? mql5 is somewhat similar as c++. is there anything i can carry from c++?

eg

13:27:18.706    4
13:27:18.900    4

Solution

  • All you need to do is pull i outside the loop:

    void OnTick()
    {
       int i = 0;
       for (; i < 5; i++)
       {
         Print(i);
       }
       // i is now one past the last index
       int last = i - 1;
    }
    

    If you know that you loop 5 times in advance, you could also obtain the last index using:

    int last = 5 - 1;