Some special Formatting %20s %-20s

C Programming Language / Overview of C Language

4600

Program:

#include <stdio.h> 
int main() 
{ 
    char str[] = "atnylaBrothers"; 
    printf("%20s\n", str); 
    printf("%-20s\n", str); 
    printf("%20.5s\n", str); 
    printf("%-20.5s\n", str); 
    return 0; 
}

Output:

      atnylaBrothers
atnylaBrothers
               atnyl
atnyl
Press any key to continue . . .

Explanation:

The given code is a C program that demonstrates the use of different format specifiers with the printf() function to print a string str in various formats.

Here's how it works:

  • The #include <stdio.h> line includes the standard input/output library in the program.
  • The main() function is the entry point of the program.
  • The character array str is declared and initialized with the string "atnylaBrothers".
  • Four different printf() statements are used to display the contents of str in different formats.
    • %20s format specifier prints the string with a minimum field width of 20 characters, right-justified.
    • %-20s format specifier prints the string with a minimum field width of 20 characters, left-justified.
    • %20.5s format specifier prints the string with a minimum field width of 20 characters and a precision of 5 characters, right-justified.
    • %-20.5s format specifier prints the string with a minimum field width of 20 characters and a precision of 5 characters, left-justified.
  • The \n character is used to insert a newline after each output is printed.
  • Finally, the return 0; statement terminates the program and returns 0 to the operating system indicating that the program executed successfully.

This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.