% -----------------------------------------------------
% runningsum1toTotal.m
% -----------------------------------------------------
% Write a program to compute the sum of all integers from 1 to N till the
% total sum is greater than or equal to M (user defined).   
% -----------------------------------------------------
% Notes: Use a while loop to perform this running sum operation. 
% -----------------------------------------------------
% Copyright and license details available at matlabmarina.com
%------------------------------------------------------

clear;
clc;

% Define the maximum value of the total sum maxVal
maxVal = 1000;

% Initialization (else 1st iteration, rsum, k will be undefined)
rsum = 0;
k = 0;

% Compute the running sum with while loop condition
while rsum < maxVal % keep adding until rsum is greater than or equal to the max
    
    rsum = rsum + k;
    k = k + 1; % increment counter by 1 each iteration
    
end

% the last iteration is the one that takes rsum beyon the maxVal
k=k-1;
rsum=rsum-k;

% display the sum of the series and N
disp('The sum of the series 1 to N is '); 
disp(rsum);
disp('The number of terms needed to reach M '); 
disp(k);
