5.2while loops 63
- What values will this code print?
1 a = 1;
2 n = 1;
3 while a < 100
4 a = a*n
5 n = n + 1;
6 end
Listing 5.6 demonstrates an example of using awhileloop to take the sum
of a geometric series (the same example posed in Exercise 2, Question 8).
Compare Listings 5.3 and 5.6.
Listing 5.6: while_loop_sum.m - Script to sum a geometric series using awhileloop
1 % while_loop_sum.m
2 % Script to sum a geometric series using a while loop
3 %
4 % Craig Warren, 01/09/2011
6 % Variable dictionary
7 % n Number of terms to sum
8 % my_sum Sum of geometric series
9 % r Constant (set to 0.5 for this example)
10 % m Loop counter
12 clear all; % Clear all variables from workspace
13 clc; % Clear command window
15 n = input('Enter the number of terms to sum: ');
16 my_sum = 0;
17 r = 0.5;
18 m = 0;
19 while m <= n
20 my_sum = my_sum + r^m;
21 m = m + 1;
22 end
23 format long % Sets display format to 15 digits
24 my_sum
Comments:
- Line 18 contains a variablem(defined outside of the loop) which is used
as a loop counter. - Lines 19–22 contain thewhileloop. The condition for the loop to execute
is that the value of the loop countermmust be less than or equal to the
number of terms to be summedn. When this condition becomes false the
loop will terminate.