Why is %c Used in C?
Just like any other programming language, C also has a fixed syntax that needs to be followed to create programs. The basic syntax of C is that users have to include the C header files first, which are <stdio.h> and <stdlib.h>. Then define a main function, which encloses all the main code of the program:
int main(void) {
}
And a print command is used to display the output. For instance, let’s try printing a letter k as an output and for that, use the below-written command inside the main function:
In the output, you can see that instead of letter k, a number is displayed as an output. Confused?
Now let’s understand this concept of why a number is printed instead of the character k, so the answer is that a computer is a machine that works on numbers so each character or letter has an equivalent machine number (ASCII code) for it. For instance; in the above example the machine equivalent number for k is 107. If a user uses %d with a character then the program will display the ASCII code of the character and not the original character.
Like %d, the %c is used to display the original character. Now let’s run the same above command to print k just replace %d with %c, as shown below:
Now in the output, you can clearly see that instead of a number, a letter k itself is printed. So, whenever users want to print a character, they can use %c inside the print command. The %c represents “character” and informs the compiler that a character output is required:
Using %c in Arrays
Now let’s print a character array using %c with a print command. In the below program, I have defined an array of 9 characters and I want to print these exact array elements one by one. For that, I have used a for loop inside which the printf command is present along with %c:
After running the program, you can see that the output has displayed the character one by one:
Now keep the program same and just replace %c with %d inside the printf command and notice the difference in the output:
Now in the output, you can see that by just changing the %c, the output has changed completely. Instead of characters, their ASCII codes are displayed:
Conclusion
The %c in C programming language is used to represent the character. Like if users want to print a character or an array of characters they can simply use %c with the printf command to inform the compiler that the output is required in the form of characters. If %d is used instead of %c, the output will change completely and instead of displaying the character output, it will display the ASCII code of each character.