Practice Midterm 2
Practice Midterm 2
Problem 1
Write a MATLAB script that uses a switch-case structure to perform one
of four arithmetic operations based on a predefined variable choice. The
two numbers involved in the operation are also predefined.
Sample Solution:
num1 = 10;
num2 = 5;
switch choice
case 1
case 2
case 3
result = num1 * num2;
if num2 == 0
else
result = num1 / num2;
fprintf('Result: %d / %d = %.2f\n', num1, num2, result);
end
otherwise
end
Problem 2
Write a MATLAB script that classifies a student’s letter grade based on a
predefined numeric score. The program must use if, elseif, and else
statements (no switch-case). Predefine a variable score, which is a
number between 0 and 100.
Use if statements to classify the grade:
• 90–100 → Grade A
• 80–89 → Grade B
• 70–79 → Grade C
• 60–69 → Grade D
• < 60 → Grade F
If the score is outside the range 0–100, display an error message.
Sample Solution:
score = 87; % You can change this value to test different scenarios
if score < 0 || score > 100
fprintf('Error: Score must be between 0 and 100.\n');
elseif score >= 90
fprintf('Score: %d → Grade: A\n', score);
else
fprintf('Score: %d → Grade: F\n', score);
end
Problem 3
Write a MATLAB program :
1. Creates a 5×5 matrix of random integers between 1 and 100 using randi.
3. Come up with a written memory map for the entire nested loop for the first 5
iterations
% Step 1: Create a 5x5 random integer matrix from 1 to 100
maxVal = A(1,1);
minVal = A(1,1);
for i = 1:5
for j = 1:5
maxVal = A(i,j);
end
minVal = A(i,j);
end
end
end
disp('Matrix:');
disp(A);