Width and Precision in printf() In C Language

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

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.

3. Input Output In C

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?