Examples

  1. Suppose we wish to sum the odd integers from 1 to 9 using a while loop. Here is Matlab code to do that:

    sum = 0;
    num = 1;
    while num <= 9
        sum = sum + num;
        num = num + 2;
    end
    disp(sum)
    We needed two variables, one to keep track of our place in the iteration, (the counter variable num) and one to keep track of the current value of the sum of the values so far (sum).
  2. Modify the above loop so it adds all the odd integers from 1 to 1,000,001:

    sum = 0;
    num = 1;
    last = 10^6 + 1;
    while num <= last
        sum = sum + num;
        num = num + 2;
    end
    disp(sum)
    Notice that the only change we had to make was in the condition (num <= 10^6 + 1) of the while loop. We added the last = 10^6+1 statement so that this value is only calculated once (before the start of the loop).