C Input and Output
printf() — Formatted Output
printf() is the standard output function in C, defined in <stdio.h>. It prints formatted text to the console using format specifiers.
| Format Specifier | Type | Example |
|---|---|---|
%d or %i | int | printf("%d", 42); |
%f | float | printf("%f", 3.14f); |
%lf | double | printf("%lf", 3.14); |
%c | char | printf("%c", 'A'); |
%s | string (char array) | printf("%s", "hello"); |
%u | unsigned int | printf("%u", 42u); |
%ld | long int | printf("%ld", 1000000L); |
%lld | long long int | printf("%lld", 9999999999LL); |
%o | Octal | printf("%o", 8); → 10 |
%x | Hexadecimal (lowercase) | printf("%x", 255); → ff |
%X | Hexadecimal (uppercase) | printf("%X", 255); → FF |
%e | Scientific notation | printf("%e", 12345.6); |
%p | Pointer address | printf("%p", ptr); |
%% | Literal % sign | printf("100%%"); |
Escape Sequences
| Escape Sequence | Meaning |
|---|---|
\n | Newline |
\t | Horizontal tab |
\\ | Backslash |
\" | Double quote |
\' | Single quote |
\0 | Null character (string terminator) |
\r | Carriage return |
\a | Alert (bell) |
#include <stdio.h>
int main() {
int age = 25;
float price = 9.99f;
double pi = 3.14159265;
char grade = 'A';
char name[] = "Alice";
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Grade: %c\n", grade);
printf("Price: %.2f\n", price); // 2 decimal places
printf("Pi: %.4lf\n", pi); // 4 decimal places
// Width and alignment
printf("\n%-10s %5d\n", "Alice", 25); // left-align name, right-align age
printf("%-10s %5d\n", "Bob", 30);
printf("%-10s %5d\n", "Charlie", 22);
// Hex and octal
printf("\n255 in hex: %x\n", 255); // ff
printf("255 in octal: %o\n", 255); // 377
printf("Percent sign: 100%%\n");
return 0;
}
scanf() — Formatted Input
scanf() reads formatted input from the keyboard. You must pass the address of the variable using the & operator (except for strings/arrays).
getchar() / putchar() and gets() / puts()
getchar() reads a single character from stdin. putchar() writes a single character to stdout. gets() is unsafe (no bounds checking) — use fgets() instead.
#include <stdio.h>
int main() {
int age;
float salary;
char name[50];
// scanf reads formatted input; & gives the address of the variable
printf("Enter your name: ");
fgets(name, sizeof(name), stdin); // safer than gets()
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your salary: ");
scanf("%f", &salary);
printf("\nName: %s", name);
printf("Age: %d\n", age);
printf("Salary: %.2f\n", salary);
// getchar / putchar — single character I/O
printf("\nEnter a character: ");
getchar(); // consume leftover newline from scanf
char ch = getchar();
printf("You entered: ");
putchar(ch);
putchar('\n');
// puts — prints string with automatic newline
puts("Done!");
return 0;
}
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.