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

Some special Formatting %20s %-20s

👁 4,324 Views
💻 Practical Program
📘 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; 
}
                        

🖥 Program 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.
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.