C program to print characters and strings in different formats.


An algorithm is given below to explain the process which is included in the C programming language to print the characters and strings in different formats.

Step 1: Read a character to print.

Step 2: Read a name at compile time.

Step 3: Output of characters in different formats by using format specifiers.

  • printf("%c
    %3c
    %5c
    ", x,x,x);
  • printf("%3c
    %c
    ", x,x);
  • printf("
    ");

Step 4: Output of strings in different formats by using format specifiers.

  • printf("%s
    ", name);
  • printf("%20s
    ", name);
  • printf("%20.10s
    ", name);
  • printf("%.5s
    ", name);
  • printf("%-20.10s
    ", name);
  • printf("%5s
    ", name);

Example

Following is the C program to print the characters and strings in different formats −

 Live Demo

#include<stdio.h>
main(){
   char x = 'T';
   static char name[20] = "Tutorials Point";
   printf("OUTPUT OF CHARACTERS

");    printf("%c
%3c
%5c
", x,x,x);    printf("%3c
%c
", x,x);    printf("
");    printf("OUTPUT OF STRINGS

");    printf("%s
", name);    printf("%20s
", name);    printf("%20.10s
", name);    printf("%.5s
", name);    printf("%-20.10s
", name);    printf("%5s
", name); }

Output

When the above program is executed, it produces the following output −

OUTPUT OF CHARACTERS
T
  T
   T
  T
T
OUTPUT OF STRINGS
Tutorials Point
Tutorials Point
Tutorials
Tutor
Tutorials
Tutorials Point

Example

Consider another program to check different format −

 Live Demo

#include<stdio.h>
main() {
   char x = 'T';
   static char name[20] = "Tutorials Point";
   printf("OUTPUT OF CHARACTERS

");    printf("%c
", x);    printf("%c
%3c
%5c
", x,x,x);    printf("%3c
%c
", x,x);    printf("%c
%3c
%5c
", x,x,x);    printf("%3c
%c
", x,x);    printf("
");    printf("OUTPUT OF STRINGS

");    printf("%.5s
", name);    printf("%-10.10s
", name);    printf("%.20s
", name);    printf("%20.10s
", name);    printf("%20s
", name);    printf("%10s
", name); }

Output

When the above program is executed, it produces the following output −

OUTPUT OF CHARACTERS
T
T
  T
    T
  T
T
T
   T
     T
   T
T
OUTPUT OF STRINGS
Tutor
Tutorials
Tutorials Point
Tutorials
Tutorials Point
Tutorials Point

Updated on: 25-Mar-2021

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements