What are C printf Practice Questions-C Programming Course With Examples

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

Input-Output in C · Free Embedded C Course

C printf Practice Questions

Thirteen printf practice questions on escape sequences, format specifiers, width and precision. Think first, then open the answer. Every output was produced by a real compiler run.

13
Practice questions
3
Diagrams
15
Minutes to read

What You Will Learn

After these printf practice questions you can:

  • Predict the output of printf calls that use \n, \t, \r and \b.
  • Choose between %d, %u, %o, %x, %c, %f, %e and %s.
  • Read a specification such as %-8.3f piece by piece.
  • Explain why the same number prints differently as a signed, unsigned or character value.
  • Avoid the format-string mistakes that cause garbage output and security bugs.

Prerequisites

Complete the earlier lectures in this chapter on printf and conversion specifiers. You need GCC or any C compiler. These printf practice questions are part of our free embedded systems course, and they make a good warm-up before the free Linux kernel development course, where printk uses nearly the same format rules.

How to Run Every printf Practice Question

Each question shows only the statements inside main. Wrap them in this template and compile with warnings enabled, because GCC will tell you when a format and its argument disagree:

#include <stdio.h>

int main(void)
{
    /* paste the statements here */
    return 0;
}
gcc -std=c17 -Wall -Wextra -o practice practice.c
./practice

Why int main(void) and not main()?

Very old C code wrote just main() and relied on a default return type. Current C standards do not allow that, and modern compilers warn or fail. Always write int main(void) and return 0;.

Reading a printf Format Specification

Every conversion has the same anatomy: a percent sign, optional flags, optional width, optional precision, optional length modifier, and one conversion letter. Learn the shape once and every printf practice question becomes mechanical.

Anatomy of %-8.3f
Piece : %–8.3f
Meaning : startleft-alignmin width 83 decimalsdouble value
Flag / partMeaningExampleResult for 42
-Left-align inside the width%-5d42 followed by 3 spaces
0Pad with zeros%05d00042
#Alternate form (prefix)%#x0x2a
+Always show a sign%+d+42
widthMinimum characters%6d4 spaces then 42
.precisionDecimals for floats, max characters for strings%.1fn/a
SpecifierExpectsShows
%d / %iintSigned decimal
%uunsigned intUnsigned decimal
%ounsigned intOctal
%x / %Xunsigned intHex in lower or upper case
%cint (a character code)One character
%schar *A string up to its terminating zero
%f / %edoubleDecimal or scientific notation
%pvoid *A pointer address
%%nothingA literal percent sign

Escape Sequences You Must Know

SequenceNameEffect on a terminal
\nNewlineCursor to the start of the next line
\tHorizontal tabCursor to the next tab stop
\rCarriage returnCursor to the start of the current line
\bBackspaceCursor one column to the left
\aAlertBeep or flash, depending on the terminal
\\BackslashPrints one backslash
\"Double quotePrints a quote inside a string
\0Null characterEnds a C string; not printable

The printf Practice Questions

For each question write your answer on paper first. Then open the box and compare. If your answer differs, run the program and find out which rule you missed.

Question 1: Tabs and new lines

    printf("Line1\nLine2\tTabbed\n");
Show the answer to question 1

Output:

Line1
Line2	Tabbed

\n ends the line. \t moves to the next tab stop, so the gap depends on your terminal settings (usually 8 columns).

Question 2: Carriage return

    printf("12345\rAB\n");
Show the answer to question 2

Output:

bytes sent : 1 2 3 4 5 \r A B \n

What the terminal draws:

AB345
Carriage return overwrites from column 0
After printing 12345 : 12345
After \r and AB : AB345

\r moves the cursor back to column 0 without erasing. The next two characters overwrite the first two.

Question 3: Backspace

    printf("Cat\br\n");
Show the answer to question 3

Output:

bytes sent : C a t \b r \n

What the terminal draws:

Car

\b moves the cursor one column left. The r then overwrites the t. Remember that nothing is deleted: the program only sends control characters and the terminal decides what to draw.

Question 4: One number, four views

    int n = 255;
    printf("%d %o %x %X %c\n", n, n, n, n, 65);
Show the answer to question 4

Output:

255 377 ff FF A

The same value 255 in decimal, octal (%o), lowercase hex (%x) and uppercase hex (%X). %c turns the code 65 into the character A.

Question 5: Signed versus unsigned

    int v = -1;
    printf("%d %u\n", v, (unsigned int)v);
Show the answer to question 5

Output:

-1 4294967295

All 32 bits of -1 are ones. Read as unsigned they mean 4294967295. On a platform with 32-bit int you get exactly this output.

Question 6: Characters are small integers

    char c = 'A';
    printf("%c %d %c\n", c, c, c + 2);
Show the answer to question 6

Output:

A 65 C

%c prints the character, %d prints its code (65), and c + 2 is the integer 67, which %c shows as C.

Question 7: Floating-point precision

    double pi = 3.14159265;
    printf("%f|%.2f|%8.3f|%-8.1f|\n", pi, pi, pi, pi);
Show the answer to question 7

Output:

3.141593|3.14|   3.142|3.1     |

Plain %f gives six decimals. %.2f rounds to two. %8.3f means at least 8 characters wide with three decimals, padded on the left. The minus in %-8.1f flips the padding to the right.

Question 8: Width, left alignment, zero padding

    printf("[%5d][%-5d][%05d]\n", 42, 42, 42);
Show the answer to question 8

Output:

[   42][42   ][00042]

Width 5 pads with spaces on the left. The - flag pads on the right. The 0 flag pads with zeros.

Question 9: Strings: width and precision

    printf("[%8s][%-8s][%.3s][%8.3s]\n", "Linux", "Linux", "Linux", "Linux");
Show the answer to question 9

Output:

[   Linux][Linux   ][Lin][     Lin]

For strings the number after the dot is a maximum count of characters, not decimals. %.3s prints only Lin, and %8.3s then right-aligns that in 8 columns.

Question 10: The return value of printf

    int n = printf("Hello\n");
    printf("%d%%\n", n);
    printf("%5.1f%%\n", 7.26);
Show the answer to question 10

Output:

Hello
6%
  7.3%

printf returns the number of characters it sent: five letters plus the newline is 6. %% prints one literal percent sign. 7.26 rounds to 7.3 at one decimal.

Question 11: Width taken from an argument

    printf("[%*d]\n", 6, 42);
    printf("[%-*d]\n", 6, 42);
    printf("[%.*f]\n", 3, 2.0 / 3);
Show the answer to question 11

Output:

[    42]
[42    ]
[0.667]

In printf the star means “take this number from the next argument”. It lets you choose the width or precision at run time. This is a different meaning from the star in scanf, which means skip.

Question 12: Integer sizes and wrap-around

    short s = 50000;
    unsigned short u = 50000;
    int big = 50000;
    printf("%d %d %d\n", s, u, big);
Show the answer to question 12

Output:

-15536 50000 50000

A short is usually 16 bits, so 50000 does not fit and wraps to 50000 – 65536 = -15536. The unsigned short and the 32-bit int hold it fine. Older C books ran on compilers where plain int was only 16 bits, and you saw the wrapped value from plain int too. Today you need short to see it.

Question 13: Bonus: alternate forms and exponent

    printf("%x %#x %#o\n", 255, 255, 8);
    printf("%e\n", 12345.678);
Show the answer to question 13

Output:

ff 0xff 010
1.234568e+04

The # flag adds the 0x prefix to hex and a leading 0 to octal. %e prints scientific notation with six decimals.

Challenge: Align a Table with printf Format Specifiers

Print the numbers 1 to 5, their squares and half values in three tidy columns separated by bars. Try it before opening the solution.

Show the solution
#include <stdio.h>

int main(void)
{
    for (int i = 1; i <= 5; i++)
        printf("%2d | %3d | %5.1f\n", i, i * i, i / 2.0);
    return 0;
}

Output:

 1 |   1 |   0.5
 2 |   4 |   1.0
 3 |   9 |   1.5
 4 |  16 |   2.0
 5 |  25 |   2.5

Widths fix the column sizes, so numbers line up on the right. Change the widths and observe how each column moves.

Common printf Mistakes and Troubleshooting

Most wrong answers in these printf practice questions come from the mistakes below. Check this table whenever your prediction and the real output disagree.

MistakeWhat you seeFix
%d with a double argumentGarbage number, undefined behaviourUse %f
%f with an int argumentGarbage or zeroCast: (double)n, or use %d
Fewer arguments than specifiersRandom values from the stackCount them; compile with -Wall
Forgetting \nPrompt and result glued together, output delayedEnd lines with \n
Single % in textMissing characters or a crashWrite %%
Passing a string where %c is expectedA strange characterUse %s, or index one character

Security: never use user text as the format

Writing printf(text) when text comes from a user, a file or the network lets that input contain % specifiers and read or even write memory. This is the format string vulnerability. Always write printf("%s", text) or puts(text). Constant format strings that you wrote yourself are fine.

char *text = get_line();   /* untrusted */
printf(text);              /* WRONG: input controls the format */
printf("%s", text);        /* RIGHT */

Best Practices for printf in Embedded Code

  • Match every specifier to the exact argument type. Use %zu for size_t, and %lu for unsigned long.
  • On small microcontrollers, a full printf with floating-point support can add many kilobytes of code. Many toolchains offer a reduced printf; check whether %f is enabled before relying on it.
  • Print fixed-width integers from <stdint.h> with the macros in <inttypes.h>, for example PRIu32.
  • Use width and zero flags for register dumps: %08x prints a 32-bit value with leading zeros.
  • Leave warnings on. GCC’s format checking catches most of the mistakes in the table above.

Key Takeaways from These printf Practice Questions

Remember these points

  • The specifier decides how bits are shown; the value itself never changes.
  • Width pads, - left-aligns, 0 zero-pads, and precision cuts strings or sets float decimals.
  • \r and \b only move the cursor. The terminal draws the result.
  • printf returns the number of characters printed.
  • The star means skip in scanf and take-from-argument in printf.
  • Never pass untrusted text as the format string.

If you could predict most outputs before opening the answers, your picture of how printf turns values into characters is solid. If not, repeat the questions you missed after a day. These printf practice questions are meant to be redone, not read once. Next in this free embedded C course we continue with formatted input and output using field widths with scanf.

Interview Questions

What is the difference between %d and %i in printf?

None in printf. Both print a signed decimal int. They differ in scanf, where %i also accepts octal and hex input.

What does printf return?

The number of characters transmitted, or a negative value if an output error occurs.

Why does printf(“%d”, 3.5) print garbage?

A double is passed but an int is expected. The mismatch is undefined behaviour.

How do you print a literal percent sign?

Use two percent signs: printf("100%%").

What does %.3s do?

It prints at most three characters of the string.

Frequently Asked Questions

How do I practise printf format specifiers?

Write a one-line program for each specifier, predict the output on paper, then compile and compare. Change the width, flags and precision and watch what moves.

What does %5.2f mean in C?

It prints a double in at least 5 characters, with exactly 2 digits after the decimal point, padding on the left with spaces.

Why does printf print -15536 for 50000?

The value was stored in a 16-bit signed type. 50000 minus 65536 wraps to -15536. On modern 32-bit int it only happens for short.

What is the difference between \r and \n?

\n moves to the next line; \r moves back to the start of the current line without advancing.

What does the star in %*d mean in printf?

The field width is read from the next int argument instead of being written in the format string.

Is printf safe to use in embedded firmware?

Yes, with care. Check code size and stack use, enable format warnings and never pass untrusted text as the format.

Is this part of a free embedded systems course?

Yes. It belongs to the free embedded systems course on EmbeddedPathashala that leads into the free embedded Linux and Linux device drivers courses.

Keep Practising in the Free Embedded C Course

Next: field widths with scanf and more formatted input. All EmbeddedPathashala courses are free, from embedded C to Linux kernel and device drivers.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *