How to align the output using justificationsin C language?

CServer Side ProgrammingProgramming

By using justifications in printf statement we can arrange the data in any format.

Right Justification

To implement the right justification, insert a minus sign before the width value in the %s character.

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

Program 1

Let’s take an example to print data in row and column-wise with the help of justification.

 Live Demo

#include<stdio.h>
int main(){
   char a[20] = "Names", b[20]="amount to be paid";
   char a1[20] = "Bhanu", b1[20]="Hari",c1[20]="Lucky",d1[20]="Puppy";
   int a2=200,b2=400,c2=250,d2=460;
   printf("%-15s %-15s\n", a, b);
   printf("%-15s %-15d\n", a1,a2);
   printf("%-15s %-15d\n", b1,b2);
   printf("%-15s %-15d\n", c1, c2);
   printf("%-15s %-15d\n", d1, d2);
   return 0;
}

Output

Names      amount to be paid
Bhanu      200
Hari       400
Lucky      250
Puppy      460

Program 2

Consider the same example by changing the justification −

 Live Demo

#include<stdio.h>
int main(){
   char a[20] = "Names", b[20]="amount to be paid";
   char a1[20] = "Bhanu", b1[20]="Hari",c1[20]="Lucky",d1[20]="Puppy";
   int a2=200,b2=400,c2=250,d2=460;
   printf("%2s %2s\n", a, b);
   printf("%5s %5d\n", a1,a2);
   printf("%2s %2d\n", b1,b2);
   printf("%5s %5d\n", c1, c2);
   printf("%2s %2d\n", d1, d2);
   return 0;
}

Output

Names      amount to be paid
Bhanu    200
Hari 400
Lucky    250
Puppy 460
Note: Alignment is note in proper if we not use correct justification
raja
Published on 05-Mar-2021 08:43:18
Advertisements