Creating Data (LOOP-END LOOP command)
A loop structure and an END CASE command within an input program can be used
to create data without any data input. The END FILE command must be used outside the loop (but within
the input program) to terminate processing.
Example
INPUT PROGRAM.
LOOP #I=1 TO 20.
COMPUTE AMOUNT=RND(UNIFORM(5000))/100.
END CASE.
END LOOP.
END FILE.
END INPUT PROGRAM.
PRINT FORMATS AMOUNT (DOLLAR6.2).
PRINT /AMOUNT.
EXECUTE.
- This example creates 20 cases with a single variable, AMOUNT. AMOUNT is a uniformly distributed number between 0 and 5,000, rounded to an integer and divided by 100 to provide a variable in dollars and cents.
- The
END FILEcommand is required to terminate processing once the loop structure is complete.
Scratch vs. Permanent Index Variables
Permanent variables are reinitialized to system-missing for each case, but scratch variables are initialized to 0 and are not reinitialized for each case; instead they retain their previous values. For loops that don't span cases, this is not an important factor, but in an input program a nested loop can persist across cases. In such instances, the index counter is not affected because it is cached and restored after execution of the loop, but the results of commands within the loop that use the value of the index variables will be different for scratch and permanent index variables.
*using scratch index variables.
INPUT PROGRAM.
LOOP #i=1 to 3.
- LOOP #j=#i to 4.
- COMPUTE var1=#i.
- COMPUTE var2=#j.
- END CASE.
- END LOOP.
END LOOP.
END FILE.
END INPUT PROGRAM.
LIST.
*using non-scratch index variables.
INPUT PROGRAM.
LOOP i=1 to 3.
- LOOP j=i to 4.
- COMPUTE var1=i.
- COMPUTE var2=j.
- END CASE.
- END LOOP.
END LOOP.
END FILE.
END INPUT PROGRAM.
LIST.
var1 var2
1.00 1.00
1.00 2.00
1.00 3.00
1.00 4.00
2.00 2.00
2.00 3.00
2.00 4.00
3.00 3.00
3.00 4.00
i j var1 var2
1.00 1.00 1.00 1.00
. 2.00 . 2.00
. 3.00 . 3.00
. 4.00 . 4.00
2.00 2.00 2.00 2.00
. 3.00 . 3.00
. 4.00 . 4.00
3.00 3.00 3.00 3.00
. 4.00 . 4.00
- Aside from the fact that the use of permanent variables as index variables results in the creation (or replacement) of those variables in the active dataset, note that many of the value for var1 (and i) are missing in the results from the input program that uses permanent variables as index variables, while none are missing from the one that uses scratch variables.
- In both cases, the inner loop ends with the
END CASEcommand, which causes the permanent variable i to be reinitialized to system-missing for subsequent iterations of the inner loop, but the scratch variable #i retains its previous value. - When control passes to the outer loop again, the
cached index value is used to set and increment i; so it has a non-missing value for the first iteration
of the inner loop, but once
END CASEis encountered, it becomes missing again until control passes to the outer loop again.
See the topic Scratch Variables for more information.