Printf() Function in C
The function printf (print-eff) is used for writing data to standard output (usually, the terminal).
A call to this function takes the general form:
printf(
format_string
,
arg1, arg2
, …)
where format_string refers to a character string containing certain required formatting information, and arg1, arg2, etc., are arguments that represent the individual input data items.
The Output Function: printf()
The format string consists of individual groups of characters, with one character group for each data input item.
Example 1:
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { printf("Hello People"); }
Conversion Specifications
The percent sign (%) symbol introduces a conversion specification, or format. A single conversion specification is a string that begins with % and ends with a conversion character. Explicit formatting may be included in a conversion specification. Otherwise defaults are used.
Conversion Characters
Conversion character | How the corresponding argument is printed |
c | as a character |
d, i | as an integer |
u | as an unsigned integer |
e | as a floating-point number, e.g. 3.141590e+00 |
E | as a floating-point number, e.g. 3.141590E+00 |
f | as a floating-point number, e.g. 3.141590 |
s | as a string |
% | with the format %% a single % is written to the output stream. |
Example 2:
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int cost=250; int price=300; printf("Answer is : %d",cost<price); printf("\n"); printf("Answer is : %d",cost==price); }
Field Width Specifier
Field width specifier is a format specifier where we define the width or the space need to be given in output which is defined using numbers with format specifiers.
Using Field width specifier with char char c=‘M’, s[]=“blue moon”;
%c | c | “M” | field width 1 |
%2c | c | ” M” | field width 2, right |
%-3c | c | “M “ | field width 3, left |
%s | s | “blue moon” | field width 9 |
%3s | s | “blue moon” | more spaced needed |
%.6s | s | “blue m” | precision 6 |
%-11.8s | s | “blue moo “ | precision 8, left |
Using Field width specifier with numbers
int i=23; double x = 32.17865753173828125;
%d | i | “123” | field width 1 |
%05d | i | “00123” | padded with zeros |
%f | x | “32.178658” | precision 6 |
%.3f | x | “32.179” | precision 3 |
%.3e | x | “3.218e+01” | e.format |
%.10.3f | x | ” 32.179″ | precision 3, right, field width 10 |
%-10.3f | x | “32.179 “ | precision 3, left, field width 10 |
Example 3:
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { float pi=3.1416; float radius=2.35; float area=radius*radius*pi; printf("Area is %f",area); printf("\n"); printf("Area is %.4f",area); }
Output:
Area is 17.349483 Area is 17.3495
Printf, Scanf live code example
Support us by sharing this post