0
0
CHow-ToBeginner · 3 min read

How to Use printf in C: Syntax, Examples, and Tips

In C, use printf to print text and variables to the screen. It takes a format string with placeholders like %d for integers and %s for strings, followed by the values to print. For example, printf("Hello %s", name); prints a greeting with a name.
📐

Syntax

The basic syntax of printf is:

  • printf(format_string, arguments...);
  • format_string: A string that can include text and format specifiers like %d, %f, %s.
  • arguments: Values that replace the format specifiers in order.

Format specifiers tell printf how to display each argument.

c
printf("format_string", arguments...);
💻

Example

This example shows how to print a string and an integer using printf. It demonstrates using format specifiers %s for strings and %d for integers.

c
#include <stdio.h>

int main() {
    char name[] = "Alice";
    int age = 30;
    printf("Name: %s\n", name);
    printf("Age: %d\n", age);
    return 0;
}
Output
Name: Alice Age: 30
⚠️

Common Pitfalls

Common mistakes when using printf include:

  • Not matching the format specifier with the argument type (e.g., using %d for a float).
  • Forgetting to include \n for a new line, causing output to run together.
  • Missing arguments for format specifiers, which can cause unpredictable output.

Always check that each format specifier has a matching argument of the correct type.

c
#include <stdio.h>

int main() {
    float pi = 3.14;
    // Wrong: using %d for float
    // printf("Pi value: %d\n", pi);

    // Right:
    printf("Pi value: %f\n", pi);
    return 0;
}
Output
Pi value: 3.140000
📊

Quick Reference

Format SpecifierDescriptionExample
%dPrints an integer (int)printf("%d", 10); // prints 10
%fPrints a floating-point number (float, double)printf("%f", 3.14); // prints 3.140000
%cPrints a single characterprintf("%c", 'A'); // prints A
%sPrints a stringprintf("%s", "hello"); // prints hello
%%Prints a percent signprintf("%%"); // prints %

Key Takeaways

Use printf with a format string and matching arguments to print formatted output.
Match each format specifier like %d or %s with the correct argument type.
Include \n in the format string to add a new line after printing.
Avoid missing or extra arguments to prevent incorrect output or crashes.
Use %% to print a literal percent sign.