Home / Programs / Some special Formatting %20s %-20s
Programming Example

Some special Formatting %20s %-20s

👁 4,324 Views
💻 Practical Program
📘 Step by Step Learning
Some special Formatting %20s %-20s

Program Code

#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 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.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.