SUNY Geneseo Department of Mathematics
Wednesday, March 8
Math 230 02
Spring 2017
Prof. Doug Baldwin
Reminder that I’m out of town from roughly noon today through the end of the week.
But you can help Nicole with her focus group discussion Friday during class time.
fprintf
You can insert the value of a variable into the message that fprintf
prints
Put a format indicator (e.g., %d
for base-10 integer, %f
for
real number, etc.) in the string where you want the value to appear, and an expression that
computes the value as a second argument to fprintf
.
You can do this with multiple values if you want.
For example, the loops in participation activity 12.1.4.
Or print the value of variable x and its square:
>> x = 17;
>> fprintf( 'x is %f and its square is %f\n', x, x^2 )
x is 17.000000 and its square is 289.000000
>> fprintf( 'x is %d and its square is %d\n', x, x^2 )
x is 17 and its square is 289
Example: Use a while loop to prompt for and read a number from the user until that number is plausibly the user’s age (assume “plausible” ages are between 3 and 133).
Relevant ideas or questions from reading
end
Here’s a script to read and validate ages:
%% Read a number from the user until it looks like a plausible age.
usrNum = input( 'Enter your age: ' );
while ( usrNum < 3 | usrNum > 133 )
fprintf( 'Try again with a new number!\n' );
usrNum = input( 'Enter your age: ' );
end
fprintf( 'Thank you for telling me your age.\n' );
Example: write a function that takes positive integers x and y as its arguments, and that returns the number of times y goes into x, along with the remainder of that division. Use a while loop to count how many times you can subtract y from x.
For instance, if x = 19 and y = 5, your function should return a quotient of 3 and a remainder of 4, because 19 = 3 × 5 + 4, if x = 10 and y = 2 your function should return a quotient of 5 and a remainder of 0, etc.
One key idea that defines the relationship between all the variables is that at the end, x = qy + r. Furthermore, r will be between 0 and y-1, i.e., 0 ≤ r < y. One way to use these ideas in the function is to start by giving q and r values that trivially satisfy x = qy + r and then use a while loop to refine them into values that also satisfy 0 ≤ r < y:
function [ q, r ] = quotientAndRemainder( x, y )
%QUOTEINTANDREMAINDER Compute the integer quotient of x divided by y and
% the remainder, for positive integers x and y.
q = 0;
r = x;
while ( r >= y )
...
end
end
See if you can figure out what should go inside the loop before our next class.
Finish the quotient-and-remainder function.
How variables in programming differ from variables in math.
Algorithms