How to align the output using justificationsin C language?

In C, justifications in printf() statements allow you to format and align output data in various ways. By using width specifiers and alignment flags, you can create well-formatted tables and organized output displays.

Syntax

printf("%-width format_specifier", value);   // Left justification
printf("%width format_specifier", value);    // Right justification (default)

To implement left justification, insert a minus sign (-) before the width value. Without the minus sign, the output is right-justified by default.

Example 1: Left Justification with Fixed Width

This example demonstrates left justification using %-15s for strings and %-15d for integers, creating a properly aligned table −

#include <stdio.h>

int main() {
    char header1[] = "Names", header2[] = "Amount";
    char name1[] = "Bhanu", name2[] = "Hari", name3[] = "Lucky", name4[] = "Puppy";
    int amount1 = 200, amount2 = 400, amount3 = 250, amount4 = 460;
    
    printf("%-15s %-15s<br>", header1, header2);
    printf("%-15s %-15d<br>", name1, amount1);
    printf("%-15s %-15d<br>", name2, amount2);
    printf("%-15s %-15d<br>", name3, amount3);
    printf("%-15s %-15d<br>", name4, amount4);
    
    return 0;
}
Names           Amount         
Bhanu           200            
Hari            400            
Lucky           250            
Puppy           460            

Example 2: Right Justification (Default)

This example shows right justification by omitting the minus sign, demonstrating how data aligns to the right within the specified field width −

#include <stdio.h>

int main() {
    char header1[] = "Names", header2[] = "Amount";
    char name1[] = "Bhanu", name2[] = "Hari", name3[] = "Lucky", name4[] = "Puppy";
    int amount1 = 200, amount2 = 400, amount3 = 250, amount4 = 460;
    
    printf("%15s %15s<br>", header1, header2);
    printf("%15s %15d<br>", name1, amount1);
    printf("%15s %15d<br>", name2, amount2);
    printf("%15s %15d<br>", name3, amount3);
    printf("%15s %15d<br>", name4, amount4);
    
    return 0;
}
          Names          Amount
          Bhanu             200
           Hari             400
          Lucky             250
          Puppy             460

Key Points

  • Use %-width for left justification and %width for right justification
  • The width value determines the minimum field width for the output
  • Proper width specification is essential for consistent table formatting
  • Left justification is commonly used for text data, while right justification works well for numerical data

Conclusion

Printf justifications in C provide powerful formatting capabilities for creating aligned output. Using appropriate width specifiers and alignment flags ensures professional-looking tables and organized data presentation.

Updated on: 2026-03-15T13:39:40+05:30

21K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements