Switch Statement Solution
letter = input('Enter your answer: ', 's');
letter = lower(letter);
switch letter
case 'y'
fprintf('Ok, continuing\n');
case 'n'
fprintf('Ok, halting\n');
otherwise
fprintf('Error\n');
end
Code Explanation:
- Line 1: Reads user input as a string
- Line 3: Converts input to lowercase using
lower()function - Line 5-11: Switch statement handles different cases
- Line 6-7: Handles 'y' input (both original and converted from 'Y')
- Line 8-9: Handles 'n' input (both original and converted from 'N')
- Line 10-11: Handles all other inputs with error message
Example Outputs:
Enter your answer: 'Y'
Ok, continuing
Enter your answer: 'n'
Ok, halting
Enter your answer: 'x'
Error
Enter your answer: 'Y'
Ok, continuing
Enter your answer: 'n'
Ok, halting
Enter your answer: 'x'
Error
⚠️ Important Note:
While this switch statement solution is elegant and works perfectly, it does not meet the original exercise requirement which specified using a "single nested if-else statement". This solution is presented as an alternative approach that demonstrates good MATLAB programming practices.
Required If-Else Solution (Meets Exercise Requirements):
letter = input('Enter your answer: ', 's');
if letter == 'y' | letter == 'Y'
fprintf('OK, continuing\n');
elseif letter == 'n' | letter == 'N'
fprintf('OK, halting\n');
else
fprintf('Error\n');
end
Comparison of Approaches:
| Feature | Switch Statement | If-Else Statement |
|---|---|---|
| Case Handling | Uses lower() to simplify |
Explicitly checks each case |
| Readability | Very clean for multiple cases | Clear but more verbose |
| Exercise Compliance | ❌ Does not meet requirements | ✅ Meets requirements |
Both solutions work correctly, but only the if-else version meets the specific exercise requirements!