# Loops are obsolete, learn arrays!, was: New to afl - loop coding

Hey guys.
I am new to afl programming.
I want you guys to help me writing code.
I defined a variable, say x that is x=0 .
now I want to make a condition that if the condition is met, the function add +1 to x, so my new x is 1 and if its met again x becomes 2 and ...

``````x=0
for( i = 0; i < BarCount; i++ )
{
if(C[i] > 0 AND c[i] < 50)
{
x0 = x0+1;
}
``````

is this correct ?

1 Like

You need to read this first http://www.amibroker.com/guide/h_understandafl.html

First and foremost thing to understand is that AFL is special because it supports array/vector processing which results in much faster and much shorter code.

The code you wrote is using traditional programming (looping) which is long and inefficient. Code is executed sequentially inside loop and it is slow to write and slow to execute. After fixing some syntax errors that you made, it would look like this:

``````x = 0; // semicolon at the end of the statement
for( i = 0; i < BarCount; i++ )
{
if(C[i] > 0 AND c[i] < 50)
{
x  = x + 1; // or you could write  x += 1; or better yet x++;
}
}
``````

But this assumes you just need to count bars when condition is met and produce just single NUMBER instead of array of bars.

If you wanted array of bars you would need to write:

``````x = counter = 0; // semicolon at the end of the statement
for( i = 0; i < BarCount; i++ )
{
if(C[i] > 0 AND c[i] < 50)
{
x[ i ]  = ++counter;
}
}
``````

Still this is inefficient.

Now start thinking array-wise - you have an array (like column in Excel) that holds running sum of bars when condition is met. Condition is simple ( C > 0 AND C < 60 ). That is your column "A". Then in column "B" you just want a running sum of column "A" that is your "x" variable. And AFL array code is just two quick lines:

``````Condition = C > 0 AND C < 50;
x = Cum( Condition ); // cumulative sum
``````

## Just look at this beauty. Short and efficient.

That all. See how much shorter AFL code is. It also runs 100x faster than loop.

You could even go down to single line:

``````x = Cum( C > 0 AND C < 50 );
``````

Or ... because prices are always > 0, you could even write

``````x = Cum( C < 50 );
``````

That is just 12 characters doing the same as your whole complicated loop.

Bottom line - don't use loops. (Almost) everything can be written in modern array (vector) way more effectively.

31 Likes

Very complete and super clear.
that was one perfect explanation.
thank you Tomasz for the code and the great software.

2 Likes