Working with Strings & Standard Functions 243
Character arrays can be initialized as follows.
a) char name [6] = { 'S ' / 'A '
,
'N ' , ' J
',
' A '
,
' Y'};
b) char name[7]= { 'S ', 'A
',
'N ',' J
',
'A ',' Y'};
Incase (a ) the output will not be ' SAN JAY' but it contains some garbage value. Arguments in this
example are initialized with [ 6 ] , which is exactly equal to a number of characters inside the braces.
The NULL character must be included and hence, the argument must be [ 7 ] instead of [ 6 ] as given
in statement (b).
8.1 Write a program to display the output when the account of N U LL character is not
considered.
# include <stdio.h># include <con±o»h>
void main()
{
char namel[ 6] {' S ' ,'A ' ,'N','J ' ,'X','Y >)t
clrscr ();
printf ("N a m e l = %s",\namel);
I
OUTPUT: SANJAY 6u*
Explanation The output of the above program would be SANJAY followed by some garbage value.
To get the correct result the argument must be [ 7 ] instead of [ 6 ] . The output can be seen as given
below after changing the argument [ 7 ] in place of [ 6 ].
The Output will be SANJAY
The argument value must be equal to number of characters + NULL character. In case the NULL
character is not taken in account (statem ent (a ) ) the string followed by the first string
(statement ( b ) ) will be displayed. The output can be observed by executing the following
program.
8.2 Write a program to display successive string in case first string is not terminated with
NULL character.
# inc lude < std io.h >
# in clu de <conio.h>
vo id m ain()
{
char namel[6]={'S ', 'A ', 'N ', ' J ', 'A ', ' Y'};
char name2 [7] = { 'S ',' A ', 'N ',' J ', 'A ',' Y' };
clrscr();
printf ("N a m el = % s",nam el);
printf ("\nNam e2 = %s",name2);
I

Get Programming and Data Structures now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.