08.01.2023 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8 ■ Arrays

void reverse(char str[]) {

void swap(char [], int, int);

int lo, hi;

for (lo = 0, hi = strlen(str) - 1; lo < hi; lo++, hi--)

swap(str, lo, hi);

} //end reverse

void swap(char str[], int i, int j) {

char c = str[i];

str[i] = str[j];

str[j] = c;

} //end swap

The following is a sample run of P8.3:

Type some data and I will reverse it

Once upon a time

emit a nopu ecnO

Reversing a string may not seem too important in its own right, but there are times when we

need to reverse the elements of an array. For example, we may have a list of student marks stored

in an array and sorted in ascending order, like this:

If we want the marks in descending order, all we have to do is reverse the array, like this:

8.9 Palindrome

Consider the problem of determining if a given string is a palindrome (the same when spelt

forwards or backwards). Examples of palindromes (ignoring case, punctuation and spaces) are:

civic

Race car

Madam, I'm Adam.

A man, a plan, a canal, Panama.

220

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!