Contents
A0A.m - If statement
% get number from user N = input('Pick an integer between 1 and 10: '); % computer picks a random number between 1 and 10 M = randi(10); % if the numbers match, the user wins! if N == M disp('you win :)') else disp('you lose :(') end
A simple code that prompts the user for a number between 1 and 10. The computer then generates a random integer also between 1 and 10 using the randi() function. The if statement then checks to see if the two numbers are equal. If they are, then the user sees a smiley face. If the numbers are not equal, then the user sees a frowny face. Notice that the logic test to see if the numbers are equal uses two equal signs "==". Common conditional tests are as follows:
if N == M % check to see if N is equal to M if N > M % check to see if N is greater than M if N >= M % check to see if N is greater than or equal to M if N <= M % check to see if N is less than or equal to M if N < M % check to see if N is less than M if N ~= M % check to see if N is not equal to M
Conditional tests may be combined using logical operators:
if A == B | A == C % if A equals B or A equals C if A == B & A == C % if A equals B and A equals C
A08B.m - More if statements
N = input('Pick an integer between 1 and 10: '); % check to see if the number is an integer between 1 and 10 % if it is, then test it against a randomly-generated number if N <1 | N > 10 disp('your number needs to be between 1 and 10') disp ('try again') elseif rem(N,1) ~= 0 % the ~= symbol means "not equal" % the rem(a,b) function returns the % remainder of a/b disp ('your number is not an integer') disp ('try again') else % computer picks a random number between 1 and 10 M = randi(10); % if the numbers match, the user wins! if N == M disp('you win :)') else disp('you lose :(') end end
This modified version of the A08A includes extra checks to see if the user typed in a number in the bounds from 1 to 10, and then checks to see if the number is an integer. If both of these conditions are true, then the computer will pick a random number and see if the user wins. Otherwise an error message will be displayed telling the user they weren't following the directions.