Welcome to this comprehensive guide on C's printf() function! This guide is designed to help both beginners and intermediates understand the ins and outs of this essential function in the C programming language. Let's dive right in!
printf()printf() is a function in the C Standard Library that allows you to print (output) formatted data to the standard output stream (usually the console). It's an indispensable tool for creating meaningful outputs in your C programs.
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
}š” Pro Tip: Always include #include <stdio.h> at the beginning of your C programs to access the standard input/output functions, including printf().
printf()printf() supports various formatting specifiers to print different types of data. Here's a quick look at the most commonly used ones:
| Specifier | Type | Example |
|-----------|-------------|--------------------------|
| %d | int | printf("%d", number); |
| %f | float | printf("%f", number); |
| %s | char* | printf("%s", string); |
| %c | char | printf("%c", character);|
š Note: Always ensure that the order of the arguments matches the order of the specifiers in the printf() function call.
printf()Now that we've covered the basics, let's explore some advanced features of printf().
You can control the minimum width and precision of output using the following flags:
| Flag | Function | Example |
|------|---------------|--------------------------|
| - | Left alignment | printf("%-10d", number); |
| 0 | Padding with zeros | printf("%010d", number); |
| . | Precision | printf("%.2f", number); |
printf() also allows you to customize the format of floating-point numbers:
#include <stdio.h>
int main() {
float number = 123.456789;
printf("%.2f\n", number); // Output: 123.46
printf("%.5f\n", number); // Output: 123.45679
printf("%10.2f\n", number); // Output: 123.46
return 0;
}Now that you've learned the basics and some advanced features of printf(), it's time to test your knowledge!
Which specifier is used to print a character in C?
What does the `-` flag do in the `printf()` function?