Printing strings with %s and printf
What you'll learn: How to use the %s format specifier to display a sequence of characters stored in an array.
The string shortcut
In previous lessons, you learned that a string in C is just an array of characters ending with a hidden "null terminator" (\0). If you wanted to print a name character by character, you would have to write a loop that visits every index of the array until it hits the end. That is tedious!
Thankfully, the printf function provides a powerful shortcut: the %s format specifier. Think of %s as a placeholder that says, "Hey C, start at this memory address and keep printing every character you find until you hit the zero-marker that signals the end of the string."
How it works in code
When you use %s, you don't need to use square brackets or specify an index. You simply provide the name of the character array. C handles the heavy lifting of iterating through the array for you.
#include <stdio.h>
int main() {
// We define a character array containing a greeting
char greeting[] = "Hello, C Programmer!";
// The %s tells printf to treat 'greeting' as a full string
printf("Message: %s\n", greeting);
return 0;
}
The "End of the Road" rule
Imagine you are following a trail of breadcrumbs. The %s specifier is like a hiker who follows those crumbs (the characters) one by one. But how does the hiker know when to stop? They look for the \0 (null terminator).
If you accidentally create a character array without that null terminator, printf won't know where to stop. It will keep wandering through your computer's memory, printing random gibberish, until it happens to crash or find a zero by sheer luck. This is why using double quotes (like "Hello") is so helpful—C automatically adds that invisible stop sign for you, making %s work perfectly every time.
Formatting with strings
Just like %d for integers, you can use %s multiple times in a single printf statement or combine it with regular text to build complete sentences dynamically. It turns a simple list of bytes into human-readable communication.
Key takeaway
Use %s in printf to display an entire character array at once without writing a loop.