C - Output Width Settings

Introduction

The w option sets output width.

It is available to all the conversion characters.

The width is the minimum amount of space provided for output.

When the output is less than the width, it's right-justified.

When the output is greater than the width, the width is ignored.

Demo

#include <stdio.h> 

int main() /*  w w w  .j a  va2  s .c o  m*/
{ 
     printf("%%15s = %15s\n","hello"); 
     printf("%%14s = %14s\n","hello"); 
     printf("%%13s = %13s\n","hello"); 
     printf("%%12s = %12s\n","hello"); 
     printf("%%11s = %11s\n","hello"); 
     printf("%%10s = %10s\n","hello"); 
     printf(" %%9s = %9s\n","hello"); 
     printf(" %%8s = %8s\n","hello"); 
     printf(" %%7s = %7s\n","hello"); 
     printf(" %%6s = %6s\n","hello"); 
     printf(" %%5s = %5s\n","hello"); 
     printf(" %%4s = %4s\n","hello"); 
     return(0); 
}

Result

As with the width option for floating-point numbers, space is padded on the left when the width is greater than the string displayed.

But when the width is less than the string's length, the full string is still displayed.

When the width value is specified for an integer, it can be used to right-align the output. For example:

printf("%4d",value); 

This statement ensures that the output for value is right-justified and at least four characters wide.

If value is fewer than four characters wide, it's padded with spaces on the left.

Unless you stick a 0 in there:

printf("%04d",value); 

In that case, the printf() function pads the width with zeros to keep everything four characters wide.

Exercise