How to use a loop to find a sum and average?
    34 views (last 30 days)
  
       Show older comments
    
    Mark Dillon
 on 11 Jul 2015
  
    
    
    
    
    Edited: Walter Roberson
      
      
 on 28 Oct 2025 at 6:23
            I am learning how to use MATLAB and have been told there is a way to create a loop that will also output the sum and the average. What I have done so far is to create an array of a random sort of numbers and printed out each element as shown below:
% Variables
x = [1.8 3.6 5.4 7.2];
fprintf('x =');
disp(x);
% For Loop
for k = 1:length(x);
    fprintf('Element %0.0f is: %0.1f \n', k, x(k));
end
What I need to figure out next is how to use the 'for' loop to also print out the sum and average.
0 Comments
Accepted Answer
  Image Analyst
      
      
 on 11 Jul 2015
        Try this:
% Variables
x = [1.8 3.6 5.4 7.2]
% For Loop
theSum = 0; % Initialize
for k = 1 : length(x);
  fprintf('Element %d is: %0.1f \n', k, x(k));
  % Accumulate the sum
  theSum = theSum + x(k);
  % Compute the running mean and print out.
  fprintf('After element #%d, the sum = %.1f, and the mean = %.3f\n\n',...
    k, theSum, theSum/k);
end
0 Comments
More Answers (2)
  Kahkashan
 on 28 Oct 2025 at 6:21
        
      Edited: Walter Roberson
      
      
 on 28 Oct 2025 at 6:23
  
      umStudents = 10;
totalMarks = 0;
marks = zeros(1, numStudents); % Pre-allocate an array to store marks
% Loop to get marks for each student
for i = 1:numStudents
    prompt = sprintf('Enter marks for student %d: ', i);
    marks(i) = input(prompt); % Get input from the user
    totalMarks = totalMarks + marks(i); % Add marks to the total
end
% Calculate the average
averageMarks = totalMarks / numStudents;
% Display the result
fprintf('The average marks of the %d students is: %.2f\n', numStudents, averageMarks);
0 Comments
See Also
Categories
				Find more on Loops and Conditional Statements in Help Center and File Exchange
			
	Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


