String

A set of character is called string.String is also array of char type.

Syntax:
char string_name[size];

Here string_name is as like as variable name. Size is the number of character of the string.At the end of the string an additional terminating character(\0) will be added. For example

Here 10 char type memory space will be created that can be imagined as follows:

name[0]
name[1]
name[2]
name[3]
name[4]
name[5]
name[6]
name[7]
name[8]
name[9]

Here name[9] will contain ‘\0’. So you are allowed to input 9 characters into name[0] to name[8]. Therefor, your string size must be the number of character you want to input plus 1. For example, if you want to input 20 character you should set size 21 as follows:

Code example:

OUTPUT

Enter a word : hello
Your entered word is : hello

NOTE:

We used ‘&’ sign before a variable inside scanf() function but in case of string we just write variable name without ‘&’ sign.

Another important thing is: we used array name and index number inside third bracket but in case of string no need to write index number. For example

But

Actually, here s represents s[0] and first character will assign to s[0], second character will assign to s[1] and third character will assign to s[2] and so on automatically. We can change this sequence by setting the starting index number. For example:

Here first character will assign to s[1], second character will assign to s[2], third character will assign to s[3] and so on.

Problem: Write a C program to input a word from keyboard and how each character followed by a new line.
Sample input: Bangladesh
Sample output:
B
a
n
g
l
a
d
e
s
h

Solution:

OUTPUT

Enter a word: Bangladesh
Entered word:
B
a
n
g
l
a
d
e
s
h


Next Previous