Week 4a Character Array
Week 4a Character Array
An array of characters is often referred to as string. A string is a sequence of characters treated as a single
entity and is terminated by a null character ('\0'). The null character (‘\0’) is automatically added by the
compiler at the end of the string. A string is actually a one-dimensional array of characters in C language.
char arrayName[arraySize];
For example,
For example,
Individual characters of the string “hello” will be assigned to the memory locations. The compiler
automatically adds the ‘\0’ at the end.
To illustrate:
0 1 2 3 4 5 6 7 8 9
h e l L o \0
When initializing the array with the individual characters, always add the null character (‘\0’) at the end.
For example,
For example,
When using an input command, the string is input as a whole, thus ‘\0’ is automatically added by the
compiler at the end.
Note that the null character is not included in counting the number of characters in a string. The null
character terminates the string or just indicates that it is already the end of the string.
A character array can be output as a whole just like the example below:
Or as individual characters just like any other type of array. However, for a character array, the null
character is used to terminate the loop instead of the size or count (i.e. the variable used to keep track
the current number of elements.)
For example,
Since the null character is used to terminate an array of characters, the size parameter, usually used in
passing arrays to functions becomes unnecessary.
Here is an example,
Practice Exercise (Ungraded)
Define the function palindrome() that returns 1 if the parameter is a palindrome, and 0 if otherwise. A
palindrome is a word, phrase, or sequence that reads the same backward as forward.
int palindrome(char str1[]);
Exercise (Graded)
Create a program to input names of two persons (preferably of different genders) and output their
resulting relationship based on the FLAMES method:
F – Friends
L – Lovers
A – Adversaries
M – Married
E – Enemies
S – Sweethearts
1. Compare the two input names and count the letters in the first input name that matches in the
second name and vice versa.
2. Determine the corresponding letter of the resulting number in the word FLAMES.
3. Add the resulting number from both names and follow step 2.
Filename: flames.c