08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8 ■ Arrays

The first while loop will read characters until it reaches F, since F is the first alphabetic

character in the data. The second loop will store

F in word[0]

i in word[1]

r in word[2]

s in word[3]

t in word[4]

Since n is incremented after each character is stored, the value of n at this stage is 5. When

the space after t is read, the while loop exits and \0 is stored in word[5], properly terminating the

string. The array word will look like this:

We can now use word with any of the standard string functions and can print it using %s, as in:

printf("%s", word);

%s will stop printing characters when it reaches \0.

The above code is not perfect – we used it mainly for illustrative purposes. Since word is of

size 10, we can store a maximum of 9 letters (plus \0) in it. If the next word is longer than 9 letters

(for example, serendipity), the code will attempt to access word[10], which does not exist,

giving an “array subscript” error.

As an exercise, consider how you would handle words that are longer than what you have

catered for. (Hint: check that n is valid before storing anything in word[n].)

To illustrate how we can work with individual characters in a string, we write a function,

numSpaces, to count and return the number of spaces in a string str:

int numSpaces(char str[]) {

int h = 0, spaces = 0;

while (str[h] != '\0') {

if (str[h] == ' ') spaces++;

h++;

}

return spaces;

} //end numSpaces

Consider the code:

char phrase[] = "How we live and how we die";

printf("Number of spaces is %d\n", numSpaces(phrase));

The first statement creates an array of just the right size to hold the characters of the string

plus \0. Since the phrase contains 26 characters (letters and spaces), the array phrase will be of

size 27, with phrase[0] containing H, phrase[25] containing e and phrase[26] containing \0.

216

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!