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

In printf, the call numSpaces(phrase) will transfer control to the function, where phrase will

be known as str. In the function, the while loop will step through the array until it reaches \0. For

each character, it will check if it is a space. If it is, 1 is added to spaces. On exit from the loop, the

value of spaces is returned as the value of the function. For the sample phrase, the value returned

will be 6.

As a matter of interest, the body of the while loop could be written as:

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

Here, h is incremented after we test if str[h] contains a space.

Exercises

1. Write a function to return the number of digits in a string str.

2. Write a function to return how many vowels there are in a string str. Hint: it

would be useful to write a function isVowel that, given a character ch, returns 1

if ch is a vowel and 0 if it is not.

8.8.1 Reverse the Characters in a String

As another example, we write code to reverse the characters in a string str. For example, if str contains

lived, we must change it to devil. To illustrate how the code will work, we picture str as follows:

We will first exchange str[0], l, and str[4], d, giving this:

Next, we will exchange str[1], i, and str[3], e, giving this:

str[2] is already in place (the middle letter does not move), so there is nothing more to do

and the method ends with str reversed.

It appears that we will need two variables: one will take on subscript values starting from 0

and increasing, while the other will take on subscript values starting from length(str)-1 and

decreasing. We will call them lo and hi. Initially, we will set lo to 0 and hi to length(str)-1.

217

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!