In this step, you'll learn how to use printf()
to format strings and various data types in C. The printf()
function provides powerful string formatting capabilities.
Let's create a new file to demonstrate string formatting:
cd ~/project
touch string_formatting.c
Enter the following code to explore different formatting options:
#include <stdio.h>
int main() {
// Basic string formatting
char name[] = "Alice";
int age = 30;
float height = 5.8;
// Simple string output
printf("Name: %s\n", name);
// Formatting with multiple variables
printf("Profile: %s is %d years old\n", name, age);
// Formatting with floating-point precision
printf("Height: %.1f meters\n", height);
// Width and alignment
printf("Name (right-aligned): %10s\n", name);
printf("Name (left-aligned): %-10s\n", name);
// Mixing different format specifiers
printf("Details: %s, %d years, %.1f meters\n", name, age, height);
return 0;
}
Compile and run the program:
gcc string_formatting.c -o string_formatting
./string_formatting
Example output:
Name: Alice
Profile: Alice is 30 years old
Height: 5.8 meters
Name (right-aligned): Alice
Name (left-aligned): Alice
Details: Alice, 30 years, 5.8 meters
Common format specifiers:
%s
: Strings
%d
: Integers
%f
: Floating-point numbers
%.1f
: Floating-point with 1 decimal place
%10s
: Right-aligned with 10 character width
%-10s
: Left-aligned with 10 character width
Let's explore more advanced formatting:
#include <stdio.h>
int main() {
// Hexadecimal and octal representations
int number = 255;
printf("Decimal: %d\n", number);
printf("Hexadecimal: %x\n", number);
printf("Octal: %o\n", number);
// Padding with zeros
printf("Padded number: %05d\n", 42);
return 0;
}
Example output:
Decimal: 255
Hexadecimal: ff
Octal: 377
Padded number: 00042