C - Output Alignment Settings

Introduction

The width value in the conversion character aligns output to the right, known as right justification.

To force the padding to the right side of the output, insert a minus sign before the width value in the %s conversion character.

For example:

printf("%-15s",string); 

This statement displays the text in the array string justified to the left.

If string is shorter than 15 characters, spaces are added to the right.

The following code displays two strings.

The first one is left-justified within a range of varying widths.

The width gets smaller with each progressive printf() statement.

Demo

#include <stdio.h> 

int main() /* ww w .j a v a  2  s.c o  m*/
{ 
     printf("%-9s as\n","asdf"); 
     printf("%-8s as\n","asdf"); 
     printf("%-7s as\n","asdf"); 
     printf("%-6s as\n","asdf"); 
     printf("%-5s as\n","asdf"); 
     printf("%-4s as\n","asdf"); 
     return(0); 
}

Result

Exercise