% gradeCalculator.m P. Conrad, demo for CISC106 Fall 2006 % input a sequence of grades (all out of 100) and calculate the average % *** Print welcome, and instructions to the user *** fprintf('Welcome to the grade averager. If you\n'); fprintf('input a sequence of grades, I can compute the average.\n'); fprintf('\n'); fprintf('I''ll ask for grades one at a time.\n'); fprintf(' * First I''ll ask you for a title for each grade (e.g. "hwk1")\n'); fprintf(' * Then I''ll ask for the score out of 100 points\n'); fprintf(' * Enter "done" for the title when you are finished\n'); fprintf('\n'); % **** set up variables grades = []; % an empty array at first; this will store all the grades count = 0; % this variable will count how many grades there are % **** Main loop to accumulate grades % Note the pattern: ask for input before the while loop, and at the % _bottom_ of the while loop. See this pattern too, on p. 150-151 of % Chapman textbook (MATLAB Programming for Engineers, 3rd Edition). title = input('Enter a title for this grade (or "done" when finished): ','s'); while (title ~= 'done') % ask user for a grade prompt = ['Enter a grade out of 100 points for ' title ': ']; thisGrade = input(prompt); count = count + 1; grades(count) = thisGrade; title = ... input('Enter a title for this grade (or "done" when finished): ','s'); end % Use a for loop to accumulate the sum (* see note at end of program) sum = 0; for (k = 1:count) sum = sum + grades(k); end average = sum / count; fprintf('The average of your %d grades is %5.1f\n',count,average); % *Note: We could have accumulated the sum inside the while loop that reads % in the data instead of doing it in a separate for loop. I did it % separately only because this program is intended to "teach" about % while loops and for loops. % % The idea is that, in general, while loops are used when % * you don't know in advance how many times the loop will run, but % * you DO know what the "stopping condition" is. % * you express the loops as "while ( stopping condition is not true) % % You use a for loop when % * you have a definite idea of how many times the loop is to be done % * you have an index variable that counts up through various values % % Also note: since this is a programming course, and not _just_ a MATLAB % course, when there is more than one way to accomplish something, I'll % generally prefer to teach the way that translates more easily into % other programming languages. For example, in this program: % % grades(count) = thisGrade; % % could be replaced with: % % grades = [ grades thisGrade ]; % % but the first way translates easily into C, C++ and Java, while the % second way is pretty specific to MATLAB. So, I'll tend to teach you % the first way more often.