Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print the percent sign(%) in C? [duplicate]

Why doesn't this program print the % sign?

#include <stdio.h>  main() {      printf("%");      getch(); } 
like image 423
Paul Filch Avatar asked Jul 21 '13 17:07

Paul Filch


2 Answers

Your problem is that you have to change:

printf("%");  

to

printf("%%"); 

Or you could use ASCII code and write:

printf("%c", 37); 

:)

like image 194
C_Intermediate_Learner Avatar answered Sep 18 '22 23:09

C_Intermediate_Learner


There's no explanation in this topic why to print a percentage sign. One must type %% and not for example an escape character with percentage - \%.

From comp.lang.c FAQ list · Question 12.6:

The reason it's tricky to print % signs with printf is that % is essentially printf's escape character. Whenever printf sees a %, it expects it to be followed by a character telling it what to do next. The two-character sequence %% is defined to print a single %.

To understand why % can't work, remember that the backslash \ is the compiler's escape character, and controls how the compiler interprets source code characters at compile time. In this case, however, we want to control how printf interprets its format string at run-time. As far as the compiler is concerned, the escape sequence % is undefined, and probably results in a single % character. It would be unlikely for both the \ and the % to make it through to printf, even if printf were prepared to treat the \ specially.

So the reason why one must type printf("%%"); to print a single % is that's what is defined in the printf function. % is an escape character of printf's, and \ of the compiler.

like image 41
macfij Avatar answered Sep 21 '22 23:09

macfij