Powered By Blogger

Wednesday 25 March 2020

Difference between Left justified and right justified format in 'c' that is "%nd" and "%-nd" in the format specifier of 'C' programming (n denotes any numerical value)

First, we need to know, what is format specifier in 'c programming?




The format specifier specifies the format of the printable or scannable variable whether it is an integer(%d), floating point (%f), character(%c), string(%s) etc. which we want to print or scan from the user.

That means it tells the compiler about the format of the taken variable which we want to print or scan.

For example: 
                     printf("%c",a);
Compiler understands that the format to print the value of the variable 'a' is a character type.
                      scanf("%f",&x);
This time compiler understands that the format to read the variable 'x' is a floating-point type.

This is simple to understand.
Now, when we add any value before any format specifier, let's see what happens.
For example:. printf("%3d",a);
Let, a=12345
Naturally ,itwill print the value of 'a' i.e 12345 though we have specified the integer limit i.e 3.
But if a=12
Then, it will print:.  (space)12
That is when the no. of number of 'a' exceeds the integer limit(%3d), then it prints the whole value of the corresponding variable i.e. 12345(n=total numbers=5).
But for the second case, as the total numbers in 'a' are less than the integer limit, then it prints the required space before the numbers to adjust the limit. For this, it prints only one space as there is total of two numbers in 'a'.

If a=356
printf("%5d",a);

Then the output will be:

(space) (space) 356

Now, coming to our main part.
At most, we have seen the use of only positive integer limits, but if we take negative, then what will happen?

Let's see, if we take the negative integer limit, then the variable value will be printed in "Left justified" way.

For example: 
x=1356
printf("%-5d",x);

The output will be:
1356(space)
That means this time, the value of the variable is printed first and thereafter the required number of spaces printed, this type of form is called "Left justified" form

So, we conclude that, if the total numbers in a variable are less than the given integer limit then, for positive limit the value will be printed in "Right justified form" and for negative limit, it will be printed in "Left justified form".

This feature is very useful to print spaces before or after any value for good visualization of output frame in 'C' programming.

Hope, this helps you. Thank you very much for reading.

No comments:

Post a Comment

Can we use pointers without specifying the data type of the pointer?

Void Pointer Yes, we can use pointers without specifying the data type of the pointers. But remember at the end of the programming, wh...