Bird
0
0

You want to create a formatted string showing a person's name and age, where age is right-aligned in a 3-character wide field. Which sprintf call achieves this?

hard📝 Application Q8 of 15
MATLAB - String Handling
You want to create a formatted string showing a person's name and age, where age is right-aligned in a 3-character wide field. Which sprintf call achieves this?
name = 'Anna'; age = 7;
Astr = sprintf('Name: %s, Age: %3d', name, age);
Bstr = sprintf('Name: %s, Age: %-3d', name, age);
Cstr = sprintf('Name: %s, Age: %03d', name, age);
Dstr = sprintf('Name: %s, Age: %d3', name, age);
Step-by-Step Solution
Solution:
  1. Step 1: Understand width and alignment

    %3d means integer right-aligned in 3 spaces; %-3d is left-aligned.
  2. Step 2: Check options

    str = sprintf('Name: %s, Age: %3d', name, age); uses %3d for right alignment; B uses left alignment; C pads with zeros; D is invalid.
  3. Final Answer:

    str = sprintf('Name: %s, Age: %3d', name, age); -> Option A
  4. Quick Check:

    Right-align integer with %3d [OK]
Quick Trick: Use %3d for right-aligned integers in width 3 [OK]
Common Mistakes:
  • Using %-3d for right alignment
  • Using %03d which pads zeros
  • Incorrect format like %d3

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More MATLAB Quizzes