Display of Strings using different formatting techniques

The  printf  function with %s format is used to display the strings on the screen.For example ,the below statement display 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,the string will be printed left justified.
printf("%-10.5s",name);


EXAMPLE

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;
printf("%-4,*s \n",y,string);

 }
for(x=3;x>=0;x--)
{
y=x+1;
printf("%-4.*s \n",y,string);

}
}

OUTPUT
U
UN
UNI
UNIX
UNIX
UNI
UN
U


Array of Strings
Array of strings are multiple strings,stored in the form of table.Declaring array of strings is same as strings,except it will have additional dimension to store the number of strings .Syntax is as follows:

char array-name[size][size];

For example,
char names[5][10]; 
where names is the name of the character array and the constant in the first square brackets will give number of string we are going to store ,and the value in second  square bracket will gives the maximum length of string.



Example
Write a program to initializes 3 names in an array of strings and display them onto monitor.

#include<stdio.h>

main()
{
int n ;
char names[3][10]={"Alex","Phillip","Collins"};
for(n=0;n<3;n++)
printf("%s\n",names[n]);

}

OUTPUT


Alex
Phillip
Collins

0 comments:

Post a Comment