60 loops
15 n = input('Enter the number of terms to sum: ');
16 my_sum = 0;
17 r = 0.5;
18 for m = 0:n
19 my_sum = my_sum + r^m;
20 end
21 format long % Sets display format to 15 digits
22 my_sum
Comments:
- Line 15 contains theinputcommand, which is used to get the number
of terms to be summed from the user. - On Line 16 a variablemy_sumis created (and set to zero) to hold the
sum of the geometric series. It is necessary to create any variables outside
of loops before using them within loops. - Lines 18–20 contain theforloop. The loop countermcounts in steps of
one from zero until the number of terms specified by the usern. - On Line 19 (the body of the loop) the new term in the sumr^mis
added to the previous value ofmy_sumand this becomes the new value
ofmy_sum. - Lines 21–22 display the result of the summation. Theformatcommand
is used to set the display to 15 digits instead of the default 4 digits so
that the result of taking more terms in the summation can be seen.
5.2 while loops
Awhileloop is similar toforloop in that it is used to repeat a command,
or set of commands. Listing 5.4 shows the syntax of awhileloop. The key
difference between aforloop and awhileloop is that thewhileloop will
continue to execute until a specified condition becomes false.
Listing 5.4: Syntax of awhileloop
1 whilecondition is true
2 statements
3 end