To learn how to print in C, start with printf from the standard input/output library. You can use it to display literal text, variables, formatted numbers, and line breaks. The smallest useful example is a complete program that writes one message to the terminal.
How to print in C: a minimal printf program
Copy these six lines in order, save the file as main.c, and compile it with a C compiler:
#include <stdio.h>
int main(void)
{
printf(“Hello, world!\n”);
return 0;
}
The #include line makes printf available. The main function is where execution begins, and return 0; reports successful completion to the operating system. The output is Hello, world! followed by a new line.
Print statement in C: format specifiers for variables
A C print statement usually combines a format string with one or more values. A format specifier begins with % and tells printf how to interpret the next argument. Use a specifier that matches the variable’s type:
const char *name = “Maya”;
char grade = ‘A’;
int count = -3;
double price = 19.95;
printf(“Name: %s\n”, name);
printf(“Grade: %c\n”, grade);
printf(“Count: %d\n”, count);
printf(“Price: %.2f\n”, price);
%s prints a null-terminated string, such as name. %c prints one character. Use %d for a signed int; it handles both positive and negative whole numbers. %f prints a floating-point value. The .2 in %.2f limits the displayed value to two digits after the decimal point.
For other common types, use %ld for a signed long, %u for an unsigned int, and %zu for size_t. A float is promoted to double when passed to printf, so %f is still the correct specifier.
Newlines and other escape sequences
Escape sequences let you include control characters inside a quoted string. The most important one is \n, which moves the cursor to the next line:
printf(“First line\nSecond line\n”);
Use \t for a horizontal tab, \\ for a backslash, \” for a quotation mark, and %% to print a literal percent sign. For example:
printf(“Name:\tMaya\nProgress: 50%%\n”);
Most terminals move to a new line when they receive \n. If output appears late when you print without a newline, the stream may be buffered; adding \n often makes terminal output appear immediately.
Common printf mistakes and return values
The format string and supplied arguments must agree. Passing a double to %d, using %s with a single character, or passing a non-string pointer to %s can produce incorrect output or undefined behavior.
For example, this is wrong because price is a floating-point value:
printf(“%d\n”, price);
Use printf(“%f\n”, price); instead. Compile with warnings enabled, such as -Wall -Wextra with GCC or Clang. These options commonly identify mismatched format specifiers before you run the program.
printf returns the number of characters it successfully writes, not including the terminating null character. It returns a negative value if an output or encoding error occurs. You can check that result when output failure matters:
if (printf(“Saved\n”) < 0) {
return 1;
}
