Different Ways of Formatting Printf in C

January 16, 2025 No Comments »






Different Ways of Formatting Printf in C

1.Display Normal Message

printf("Hello Welcome to C");

2.Display Space

printf("\t");

3.Display New Line

printf("\n");

4.Printing Value of Variable

printf("Addition of two Numbers : %d",sum");

5.Multiple Format Specifiers

printf("I Love %c %s",'c',"Programming");

Output :

I Love c Programming

6.Display Integer In Different Styles (- is space)

printf("%d",1234);
printf("%3d",1234);
printf("%6d",1234);
printf("%-6d",1234);
printf("%06d",1234);

Output :

1 2 3 4
1 2 3 4
- - 1 2 3 4
1 2 3 4 - -
0 0 1 2 3 4

7.Display String In Different Format

char str[]="Programming";    // Length = 11
printf("%s",str);
printf("%10s",str);
printf("%15s",str);
printf("%-15s",str);
printf("%15.5s",str);
printf("%-15.5s",str); 

Output - ) is space

Programming
Programming
----Programming
Programming----
----------Progr
Progr----------

Summary :

Suppose str = “Programming”;

%s      : Display Complete String
%10s    : 10 < Length therefor Display Complete String
%15s    : Display Complete String with 4 spaces Alignment:Right
%-15s   : Same of Above But Justification = Left
%15.5s  : 15-5 = 10 spaces and show first 5 characters Align : R
%-15.5s : 15-5 = 10 spaces and show first 5 characters Align : L

Leave A Response