C Language

Printf Function

In C Language by Baqir AliLeave a Comment

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("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”;

%cc“M”field width 1
%2cc” M”field width 2, right
%-3cc“M “field width 3, left
%ss“blue moon”field width 9
%3ss“blue moon”more spaced needed
%.6ss“blue m”precision 6
%-11.8ss“blue moo “precision 8, left

Using Field width specifier with numbers

int i=23;
double x = 32.17865753173828125;
%di“123”field width 1
%05di“00123”padded with zeros
%fx“32.178658”precision 6
%.3fx“32.179”precision 3
%.10.3fx” 32.179″precision 3, right, field width 10
%-10.3fx“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("Area is %.4f",area);


Area is 17.349483
Area is 17.3495

Printf, Scanf live code example

Support us by sharing this post

About the Author

Baqir Ali

Facebook Twitter

Hi, I am Baqir Ali ---- Blogger, Programmer, and a Teacher. I am currently working as a Programmer for Softnat Technologies. I have tons of ideas and data to share with you all via blogging.

Leave a Comment