how to center align a number using printf

if 1 is given output=" 1 "
if 12 is given output=" 12"
if 123 is given output=“123”
thank you

Could you please provide more details.How exactly do you wish to output ?

printf doesn’t have a centre align option. But it has a left align and a right align option. But if you are really in need of a centre align feature, you can write your own custom function for that purpose. Here is a sample. :smiley:


void centrePrint(int n, int width)
{
    char s[20] = {'\0'};
    int len;
    sprintf(s, "%d", n);
    len = strlen(s);
    if (len >= width)
        printf(s);
    else
    {
        int remaining = width - len;
        int spacesRight = remaining / 2;
        int spacesLeft = remaining - spacesRight;
        printf("%*s%s%*s", spacesLeft, "", s, spacesRight, "");
    }
}

2 Likes

And this can be customized for not just an integer, but for any datatype. The idea behind is what matters :wink:

//