Left-justify printf output

This example program demonstrates how to left-justify output in printf in C.

#include <stdio.h>

int main ()
    int x = 345;
    const char * y = "monkeys";

    /* Demonstrate with numbers. */
    printf ("<%d> is not justified.\n", x);
    printf ("<%5d> is right-justified.\n", x);
    printf ("<%-5d> The minus sign makes it left-justified.\n", x);
    /* Demonstrate with strings. */
    printf ("'%s' is not justified.\n", y);
    printf ("'%10s' is right-justified.\n", y);
    printf ("'%-10s' is left-justified using a minus sign.\n", y);

    return 0;


It outputs the following:

<345> is not justified.
<  345> is right-justified.
<345  > The minus sign makes it left-justified.
'monkeys' is not justified.
'   monkeys' is right-justified.
'monkeys   ' is left-justified using a minus sign.

Copyright © Ben Bullock 2009-2018. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer