Printf function can be used to display the value of a variable on the output screen.
How to display on the output screen. 2 informations are important for that. They are,
1. format specifier
2. variable name
If you want to print the value of an integer variable, the format specifier for integer is %d.
int %d
Syntax:
printf(“%d”,int_variable_name);
If you want to print the value of a float variable, the format specifier of float is %f.
float %f
Syntax
printf(“%f”,float_variable_name);
If you want to print the value of a double variable, its format specifier is %lf.
double %lf
Syntax
printf(“%\f”,double_variable_name);
If you want to print the value of a character variable, its format specifier is %c.
char %c
Syntax:
printf(“%c”,character_variable_name);
How does printf print variable value?
int i=7;
printf(“value of i:%d\n”,i);
Output
Value of i: 7
First it checks the statement int i=10.
A memory is created for the integer variable i and stores its value 7.
Printf(“value of i:%d\n”,i);
In this statement, the first value of i: will be printed on the output screen. %d is the integer format specifier. Next to that are i. Here the value of variable i is 7. It will take that value and put it where %d is.
In output we have,
The value of i:7 will be displayed.
Multiple Value Print The One Statement
int x=7;
char y='a';
printf(“x=%d\t y=%c\t”,x,y);
Output:
x=7 y=a
x is an integer variable whose value is 7.
First, memory is created for the integer variable x. The value 7 is stored in the memory created.
Next, the memory is created for the character variable y, in which the character a is stored.
printf(“x=%d\t y=%c\t”,x,y);
First "x =" is printed and then there is %d. After seeing %d, it fetches the value 7 in x next to Comma and puts it where %d is.
Next, \t is 4 spaces away from the cursor. There, the message "y=" is printed. Next is %c. After seeing this, the character 'a' is stored in the second variable y next to Comma. fetches and places it where %c is.
Now on the output screen,
x=7 y=a
are printed.
From this we know that we can print by giving values higher than one in a prinf().