We can also emulate for loops. A for loop in most programming languages looks similar to the following:
int sum = 0;
for(int i = 1; i = 5) {
sum = sum + i
i = i + 1
}
In this pseudo-code, we declare a variable, sum, and set the starting value for sum to 0. We then have the declaration of our for loop header, where we specify that we want to start iterating with the i variable equaling 1 and stop iterating when i equals 5. The body of the for loop is encapsulated by brackets: { and }. In this body, we add i to the value of sum each time we go through the loop, and we increment i by 1. Thus, we would expect this loop to iterate 5 times and for the value of sum to be 15 once the loop finishes executing: (0+1) -> (1+2) -> (3+3) -> (6+4) -> (10+5) = 15.
To emulate this for loop, do the following:
- Create the following measure:
For Loop =
VAR __n = 5
VAR __sum = 0
VAR __loopTable = GENERATESERIES(1,__n)
VAR __loopTable1 =
ADDCOLUMNS(
__loopTable,
"__Sum",
__sum + SUMX(
FILTER(
__loopTable,
[Value]<=EARLIER([Value])
),
[Value])
)
RETURN
MAXX(
FILTER(__loopTable1,[Value]=__n),
[__sum]
)
- On a Report page, create a Card visualization and place the While Loop measure into the Fields area
The For Loop measure follows a very similar pattern to the While Loop measure, using table rows in the table variable, __loopTable, as the iterations of the loop.