String Formatting in C Language

 

The printf function with %s format is used to display the strings on the screen.

For example, the below statement displays entire string:

printf(“%s”, name);

We can also specify the accuracy with which character array (string) is displayed.

For example, if you want to display first 5 characters from a field width of 15 characters,

you have to write as:  printf(“%15.5s”, name);

If you include minus sign in the format (e.g. % –10.5s), the string will be printed left justified.

printf(“% -10.5s”, name);

Write a program to display the string “UNIX” in the following format.

U
UN
UNI
UNIX
UNIX
UNI
UN
U

# include <stdio.h>

main()

{

int x, y;

static char string[ ] = “UNIX”;

printf(“\n”);

for( x=0; x<4; x++)

{

y = x + 1;

/* reserves 4 character of space on to the monitor and minus sign is for left justified*/

printf(“%-4.*s \n”, y, string);

/* and for every loop the * is replaced by value of y */

/* y value starts with 1 and for every time it is incremented by 1 until it reaches to 4*/

}

for( x=3; x>=0; x- -)

{

y = x + 1;

printf(“%-4.*s \n”, y, string);

/* y value starts with 4 and for every time it is decrements by 1 until it reaches to 1*/

}

}

OUTPUT

 

U
UN
UNI
UNIX
UNIX
UNI
UN
U

 

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: