printf - formatted output#
printf prints a format string in which placeholders (format specifiers) are replaced by values, in order:
printf("format string", value1, value2, ...);
| Specifier | Type | Example output |
|---|---|---|
%d / %i |
int | 42 |
%f |
float / double | 3.140000 |
%.2f |
2 decimal places | 3.14 |
%e |
scientific notation | 3.140000e+00 |
%c |
char | A |
%s |
string | Indore |
%x / %o |
hexadecimal / octal | 2a / 52 |
%p |
pointer (address) | 0x7ffd... |
%% |
a percent sign | % |
Decimal: 42, Hex: 2a, Octal: 52 Pi: 3.141590 | 3.14 | 3.141590e+00 Char: V, String: Vindhyaedu
Width, precision and alignment - making tables#
%[flags][width][.precision]specifier
- width - minimum characters; the value is padded with spaces on the left (right-aligned).
-flag - left-align inside the width.0flag - pad numbers with zeros.- .precision - digits after the decimal point (for
%f), or max characters (for%s).
Item | Qty| Price Notebook | 3| 45.50 Pen | 12| 10.00 Calculator| 1| 649.00 Roll no: 0007
%8.2f का मतलब: कुल कम से कम 8 जगह लो और दशमलव के बाद 2 अंक दिखाओ। %-10s में - का मतलब है text को बाईं ओर (left) align करो। इससे बिल जैसी साफ़ table बनती है।
scanf - reading input#
scanf reads values typed by the user and stores them in variables. You pass the address of each variable using &:
Enter age and height: Age 21, height 5.9
The box under the code is the program input (what a user would type). Change the numbers and run again. Values can be separated by spaces or new lines.
Forgetting & (scanf("%d", age);) does not cause a compile error but crashes or corrupts memory at run time. Strings (char name[20]) are the exception - an array name is already an address, so no &.
Reading characters and words#
Grade A from Bhopal
The space before %c in " %c" tells scanf to skip any whitespace (like the Enter key left over from the previous input). Without it, %c often reads that leftover newline. %29s limits the word to 29 characters so it fits in city[30] (one byte is needed for the end marker \0).
Reading a full line with fgets#
%s stops at the first space. To read a whole line (a full name, an address), use fgets:
Welcome, Ravi Kumar Sharma!
What scanf returns#
scanf returns how many values it read successfully. You can use it to check input:
Please enter two numbers (read 1)
Summary#
printfuses format specifiers; width/precision/flags give neat, aligned output.scanfneeds addresses:&variable(but not for arrays/strings).- Use
%lfto read a double;" %c"to skip leftover whitespace before a char. fgetsreads a full line including spaces.