by Dinesh Thakur Category: Type And Variables

In general, the sign is not displayed with positive values. However, if we desire to display the + sign, we may add it in the control string. If the display is desired to be left justified as well as with+ sign, add + or ++between the % sign and the conversion character; for example, the following code for integers.

printf("|%+20d|\n", K);

will display the value of K in right justification in width 20 with + sign before it, and, the following code

printf("|%-+20d|\n", K);

will display the value of K in left justification in width 20 with+ sign before it. For display of -ve sign it has to be put with the variable name as illustrated in the following program (because in formatting string it is for left justification). The vertical bars have been purposely included to show the placement of output between the specified widths. The space between bars represents the width of display,

Illustrates display of +ve or -ve sign in output.

#include <stdio.h>

    int K = 64;
    printf("|%+20d|\n", K);  // right justification with +ve sign
    printf("|%-20d|\n", K);  // left justification with no sign
    printf("|%-+20d|\n", K); // left justification with +ve sign
    printf("|%+-20d|\n", K); // left justification with +ve sign
    printf("/%20d|\n", -K); // right justification with -ve sign
    printf("|%-20d|\n", -K); // left justification with -ve sign

    Explicit Display of + and - Signs in Output in C

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Search Content