Programming basics
Loops
There are several more complicated structures called loops.
In case of if condition - statement executes only once if satisfied. Conditions inside loops are executed several times.
First example is FOR loop.
snowBall = 0;
for(a=1; i<11; i++) {
snowBall += a;
}
In this example loop will repeat 10 times – the for statement will count variable a from 1 to 10 every time incrementing it. So snowBall values will be 1 , 3 , 6, 10 and so on.
While loop will repeat as many times as necessary to satisfy the predefined condition.
snowBall = 1;
while(snowBall < 100) {
snowBall = snowBall*2;
}
snowBall variable will increase every loop - 1, 2, 4, 8, 16, 32, 64 …. And 128. After that condition is satisfied and it's impossible to enter loop any more. If we change a while condition to 1000, loop will make three more turns - 256, 512 and 1024.
Do loop is very similar – the only difference that even if the condition is not satisfied from the very beginning loop still will execute once.
snowBall= 1024;
do {
snowBall = snowBall * 2;
} while (snowBall <100)
As a result variable snowBall will receive a value 1024