# Loop¶

loop (maxLoopCount)
loopBody


Bitcoin script does not provide looping constructs natively for security reasons. sCrypt achieves looping by repeating the loop body maxLoopCount times. For example, the loop

loop (10) {
x = x * 2;
}


is equivalently unrolled to

x = x * 2;
x = x * 2;
x = x * 2;
x = x * 2;
x = x * 2;
x = x * 2;
x = x * 2;
x = x * 2;
x = x * 2;
x = x * 2;


Because loop unrolling is done at compile time, the compiler must know maxLoopCount, which has to be a constant number.

If maxLoopCount is set too small, the contract may not work correctly. If maxLoopCount is set too large, the resulting script is bloated unnecessarily and costs more to execute. There are a number of ways to choose the right maxLoopCount judiciously. One way is to simulate the contract off chain and find the number of loops. Another way is to exploit the characteristics of the looping itself. For example, if a loop iterates over each bit of a sha256 hash, maxLoopCount is 256.

## Access loop index¶

int i = 0;
loop (3) {
// i becomes the loop index
i = i + 1;
x = x * 2;
}


## Conditional loop¶

loop (3) {
// place condition here
if (x < 8) {
x = x * 2;
}
}


## break¶

bool done = false;
loop (3) {
if (!done) {
x = x * 2;
if (x >= 8) {
done = true;
}
}
}