0
0
MATLABdata~20 mins

String formatting (sprintf) in MATLAB - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
sprintf Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
AValue: 7, Pi approx: 3.14159
BValue: 7, Pi approx: 3.14
CValue: 7, Pi approx: 3.1
DValue: 7, Pi approx: 3
Attempts:
2 left
💡 Hint
Look at the %.2f format specifier; it rounds to two decimal places.
Predict Output
intermediate
2: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);
ADate: 5/9/2024
BDate: 05/9/2024
CDate: 05/09/2024
DDate: 5/09/2024
Attempts:
2 left
💡 Hint
The %02d means pad with zeros to 2 digits, %04d pads to 4 digits.
Predict Output
advanced
2: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);
AHex: FF, Oct: 10, Char: A
BHex: ff, Oct: 8, Char: 65
CHex: FF, Oct: 8, Char: A
DHex: 255, Oct: 10, Char: 65
Attempts:
2 left
💡 Hint
Remember %X prints uppercase hex, %o prints octal, %c prints character from ASCII code.
Predict Output
advanced
2: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);
A|Hi | 42|
B| Hi| 42|
C|Hi |42 |
D|Hi| 42|
Attempts:
2 left
💡 Hint
%-10s means left-align string in 10 spaces; %5d means right-align integer in 5 spaces.
🧠 Conceptual
expert
2:00remaining
Understanding sprintf behavior with multiple format specifiers
Consider this MATLAB code:
str = sprintf('%d %d %d', 1, 2); disp(str);

What happens when you run this code?
AIt prints '1 2' ignoring the last format specifier.
BIt prints '1 2 0' because missing arguments default to zero.
CIt prints '1 2 2' repeating the last argument.
DIt raises an error because there are fewer input arguments than format specifiers.
Attempts:
2 left
💡 Hint
Check how MATLAB handles missing arguments for sprintf.