Printing chars with %c
What you'll learn: How to display individual text characters in your console using the printf function and the %c placeholder.
The character container
In C, the char data type is like a tiny box designed to hold exactly one letter, digit, or symbol. While we use double quotes (" ") for strings of text, we must use single quotes (' ') to define a single character.
However, storing a character is only half the battle; we need a way to tell the computer, "Hey, don't look at this as a number—look at it as a letter." This is where the %c format specifier comes in.
Using the %c placeholder
When you use printf, you use placeholders to act as "reserved seats" for your variables. If you use %d, C treats the data as a decimal integer. If you use %c, C looks at the underlying numeric value and translates it into its corresponding character from the ASCII table.
Think of %c as a translator. If you have the number 65, the %c translator looks at its chart and says, "In the world of text, 65 means a capital 'A'."
#include <stdio.h>
int main() {
char grade = 'A';
char symbol = '$';
// The %c tells printf to format the variable as a character
printf("Your grade is: %c\n", grade);
printf("The total cost is: %c50\n", symbol);
return 0;
}
Why not just use text?
You might wonder why we don't just type the letter directly into the print statement. By using char variables and %c, your programs become dynamic. Your code can change the character stored in the variable based on user input or logic—like changing a player's icon on a map or updating a letter grade—while the printf statement remains exactly the same.
Just remember: %c is for single characters only. If you try to jam a whole word into a char or use %c for a string, the compiler will get confused. One box, one character, one %c.
Key takeaway
Use the %c format specifier within printf to display a single char variable formatted as a text symbol.