(Alphabetizing Strings) Use the string-comparison functions discussed in Section 22.10 and the techniques for sorting arrays developed in Chapter 7 to write a program that alphabetizes a list of strings. Use the names of 10 towns in your area as data for your program.
What will be an ideal response?
```
#include
#include
using namespace std;
const int SIZE = 50;
void insertionSort( char [][ SIZE ] ); // prototype
int main()
{
char array[ 10 ][ SIZE ]; // character array
int i; // index
// loop to take in 10 strings
for ( i = 0; i < 10; i++ )
{
cout << "Enter a string: ";
cin >> &array[ i ][ 0 ];
} // end for
// call function insertionSort to sort the array content
insertionSort( array );
cout << "\nThe strings in sorted order are:\n";
// print out the sorted array
for ( i = 0; i < 10; i++ )
cout << &array[ i ][ 0 ] << endl;
return 0; // indicates successful termination
} // end main
// sorting function
void insertionSort( char a[][ SIZE ] )
{
char insert[ SIZE ]; // temporary variable to hold element to insert
// loop over elements
for ( int next = 1; next < 10; next++ )
{
strcpy( insert, a[ next ] ); // store value in current element
int moveItem = next; // initialize location to place element
// search for place to put current element
while ( moveItem > 0 && strcmp( a[ moveItem - 1 ], insert ) > 0 )
{
// shift element right one slot
strcpy( a[ moveItem ], a[ moveItem - 1 ] );
moveItem--;
} // end while
strcpy( a[ moveItem ], insert ); // place inserted element
} // end for
} // end function insertionSort
```
Enter a string: Weymouth
Enter a string: Braintree
Enter a string: Quincy
Enter a string: Sudbury
Enter a string: Wayland
Enter a string: Weston
Enter a string: Hanson
Enter a string: Bourne
Enter a string: Bridgewater
Enter a string: Carver
The strings in sorted order are:
Bourne
Braintree
Bridgewater
Carver
Hanson
Quincy
Sudbury
Wayland
Weston
Weymouth
You might also like to view...
How many times is the loop body of the for statement executed?
Assume that all variables are of type int and that y and z are initialized to 0. ``` for (int i = 0; i < 100; ++i) { cin >> x; y += x; if ( x % 2 == 0 ) ++z; } ``` a. once b. 99 times c. 100 times d. until a number larger than 100 is entered
One of the commands to log into a remote host is:
a: rshell b: login c: rlogin d: rhost e: login remote
The____________________ function returns a Boolean value of TRUE if a given value exists in an array.
Fill in the blank(s) with the appropriate word(s).
What is wrong with the following code? x=1; while (x<5); { System.out.println (x); x++; }
A. Syntax error in the println method B. Incorrect use of prefix increment operator C. Semicolon at the end of the while expression D. Incorrect initialization