A04.m - For Loop

% get info from user
N = input('Enter number of terms in sum:  ');

% initialize sum to zero
s = 0;

% Use a for loop to add numbers from 1 to N
for n=1:N
    s = s + n;
end

% display result to command window
% notice that because the variables N and s are integers, we use the %i
% formatting in the fprintf statement
fprintf('\n')
fprintf('Sum of numbers from 1 to %i = %i \n',N,s)

Download A04.m

This simple program calculates the sum of integers from 1 to N using a for loop. First, the user is prompted to enter the number N. The variable s is going store the sum of the integers. It is initialized to zero. In the for looop, a counter variable n is initialized to n=0 and then incremented n=1, 2, 3, ... until n reaches N. Every time the loop is executed, the integer n is added to the running sum s. Once n reaches N the loop terminates and the variable s will contain the sum of the integers 1 + 2 + 3 + ... + (n-1) + n. The final result is displayed to the screen.


Monkey Home   |    Prev   |   Next