If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In the printf
function of the C programming language, the width and precision are optional parameters that can be used to control the minimum width and the number of decimal places for a given data type.
The width parameter is specified by a number immediately following the %
symbol and before the conversion specifier. It sets the minimum width of the field in which the value will be printed. If the value to be printed is shorter than the specified width, it will be padded with spaces on the left (or right if specified) to reach the specified width.
For example, the following code will print the value of x
with a minimum width of 10 characters:
Copy code
int x = 5;
printf("The value of x is %10d", x);
This will output:
Copy code
The value of x is 5
The precision parameter is specified by a .
(dot) followed by a number immediately following the %
symbol and before the conversion specifier. It sets the number of decimal places for floating-point numbers and the number of characters for strings.
For example, the following code will print the value of pi
with a precision of 2 decimal places:
Copy code
float pi = 3.14159;
printf("Pi is approximately %.2f", pi);
This will output:
Copy code
Pi is approximately 3.14
When working with strings, the precision parameter can be used to limit the number of characters displayed
Copy code
printf("%.3s", "Hello World");
This will output:
Copy code
Hel
You can also use width and precision together in a single format specifier:
Copy code
printf("The value of x is %10.2f", x);
This will output:
Copy code
The value of x is 5.00
It will take 10 characters in width and 2 decimal places to the right.
Comments: 0