Challenge - 5 Problems
sprintf Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of sprintf with integer and float formatting
What is the output of the following MATLAB code?
str = sprintf('Value: %d, Pi approx: %.2f', 7, 3.14159); disp(str);MATLAB
str = sprintf('Value: %d, Pi approx: %.2f', 7, 3.14159); disp(str);
Attempts:
2 left
💡 Hint
Look at the %.2f format specifier; it rounds to two decimal places.
✗ Incorrect
The %d formats the integer 7 as is. The %.2f rounds the float 3.14159 to two decimal places, resulting in 3.14.
❓ Predict Output
intermediate2:00remaining
Using sprintf to format a date string
What will be the output of this MATLAB code?
day = 5; month = 9; year = 2024; str = sprintf('Date: %02d/%02d/%04d', day, month, year); disp(str);MATLAB
day = 5; month = 9; year = 2024; str = sprintf('Date: %02d/%02d/%04d', day, month, year); disp(str);
Attempts:
2 left
💡 Hint
The %02d means pad with zeros to 2 digits, %04d pads to 4 digits.
✗ Incorrect
The day and month are padded with zeros to two digits, so 5 becomes 05 and 9 becomes 09. The year is padded to 4 digits, but it is already 4 digits.
❓ Predict Output
advanced2:00remaining
Output of sprintf with mixed format specifiers
What is the output of this MATLAB code?
str = sprintf('Hex: %X, Oct: %o, Char: %c', 255, 8, 65); disp(str);MATLAB
str = sprintf('Hex: %X, Oct: %o, Char: %c', 255, 8, 65); disp(str);
Attempts:
2 left
💡 Hint
Remember %X prints uppercase hex, %o prints octal, %c prints character from ASCII code.
✗ Incorrect
255 in hex is FF, 8 in octal is 10, and ASCII code 65 is character 'A'.
❓ Predict Output
advanced2:00remaining
sprintf with width and left alignment
What will this MATLAB code display?
str = sprintf('|%-10s|%5d|', 'Hi', 42); disp(str);MATLAB
str = sprintf('|%-10s|%5d|', 'Hi', 42); disp(str);
Attempts:
2 left
💡 Hint
%-10s means left-align string in 10 spaces; %5d means right-align integer in 5 spaces.
✗ Incorrect
The string 'Hi' is left aligned in a 10-character field, padded with spaces on the right. The number 42 is right aligned in a 5-character field, padded with spaces on the left.
🧠 Conceptual
expert2:00remaining
Understanding sprintf behavior with multiple format specifiers
Consider this MATLAB code:
What happens when you run this code?
str = sprintf('%d %d %d', 1, 2); disp(str);What happens when you run this code?
Attempts:
2 left
💡 Hint
Check how MATLAB handles missing arguments for sprintf.
✗ Incorrect
MATLAB requires the number of arguments to match the number of format specifiers. Missing arguments cause an error.