Loops

If we want to repeatedly execute a bunch of commands for a million times, we can use the for loop
s = 0;  // initialize s 
for k = 1 : 1000000
    s += k;      // add k to s --- equivalent to "s = s + k"
end
The above loop compute the sum

$\displaystyle \sum_{k=1}^{1000000} k
$

The while loop enables us to repeatedly execute a bunch of commands as long as a condtion is satisfied
s = 0;
k = 1;
while k <= 1000000   // do the following as long k is less than a million
    if k % 2 != 0    // k % 2 is the remainder of k/2
       s += k;
    end
    ++k;   // increment k, same as k = k + 1;
           // without the increment, k will stays as 1 and loop runs forever
end
The above while loop sums up all the odd numbers between 1 and a million; it is equivalent to the following for loop
s = 0;
for k = 1 : 2 : 1000000
    s += k;
end



oz 2009-12-22