Exercise 3

profilegina123
execution_control_and_string_manipulation.pdf

EXECUTION CONTOL AND STRING MANIPULATION

Please note that the material on this website is not intended to be exhaustive. This is intended as a summary and supplementary material to required textbook.

INTRODUCTION

Recall that execution control involves executing parts of a program when certain conditions are true/false. String manipulation is heavily used to process text files.

BASIC EXECUTION CONTROL STRUCTURES

Execution control structures include:

Sequential execution, in which one statement is executed, and then the next, then the next, and so on. Alternative (or conditional) execution, in which a condition is tested, and if true, one block of code is executed; if false, perhaps a different block of code is executed. Repetition (or looping) in which a block of code is repeatedly executed until a condition become true/false. Subprograms (or functions) in which a separate routine is called to perform often required tasks.

Almost all of these execution structures will involve blocks of code, and both the alternative and repetition structures will involve the test of conditions (by means of logical expressions).

When writing code that implements execution control, a convention is usually followed that involves indenting blocks of code to set them off; this convention is not required by C++; the convention makes the program more readable.

Recall that conditions and expressions evaluate to true/false or some numeric value, and that expressions can make extensive use of numeric and logical operators. Recall also that extensive use of parentheses can be avoided (but not completely) if you use the rules of precedence. Lastly, recall that blocks of code are contained within curly braces.

Most alternative execution structures use the keyword if (and its variants) and the keyword switch.

USING if AND ITS VARIANTS

The if keyword requires an expression that must be evaluated. The simplest use of if is: if (expression) statement;

int count; ... if (count == 0) count = 1; ...

More often than not you will want to execute several statements if the expression evaluates to true:

int count1, count2; ... if (count1 == 0) { count1 = 1;

count2 = 0; }

Note that multiple statements have to be included in a block; also note that the statements within the block are indented (indentations are not required, but are used to enhance readability).

A variant of if is used when you want to execute one (or more statements) when the expression is true, and another statement (or set of statements) when the expressions is false: if (expression) . . . else . . .

int count1, count2; ... if (count1 == 0) { count1 = 1; count2 = 0; } else { count1 = 0; count2 = 1; }

Another variant of if allows you to use several expressions and take 3 or more alternative paths, depending of the values of the expressions. This variant uses the construction: if (expression1) . . . else if (expression2) . . . else . . .

int count1, count2, count3; ... if (count1 == 0 && count2 == 1) { count1 = 1; count2 = 0; count3 = 0; } else if (count2 == 0 && count3 ==1) { count1 = 0; count2 = 1; count3 = 0; } else { count1 = 0; count2 = 0; count3 = 1; }

Of course, you can add as many else if conditions you want.

USING THE switch

The switch keyword is just another way of coding the: if . . . else if . . . else if . . . else . . . construction. It also uses an expression to determine which path to take, but there are some restrictions. The expression cannot use logical operators (such as the && in the above example). The switch has the following general form:

switch (expression) { case value1: ... break; case value2: ... break;

case valueN: ... break; ... default: ... }

The switch structure has several different and noteworthy features. The entire switch must be placed in one block of code (using curly braces). Inside the structure are blocks of code delimited by the case ... break; construction (curly braces are not required).

Each break causes the code to exit the switch. If you leave the break out, your program will "fall into" the next case (and sometimes this is desirable). The last case, the default case, has no break (and none is needed because it is always last in the switch).

char aircraftType; ... switch (aircraftType) { case 'M': cout << "This is a military aircraft" << endl; break; case 'C': cout << "This is a commercial aircraft" << endl; break; case 'P': cout << "This is a privately owned aircraft" << endl; break; default: cout << "Unknown aircraft type" << endl; }

NESTED if STATEMENTS

You have to be especially careful when using nested ifs, as your best intentions can have unexpected results. As a general practice for safer programming, enclose all blocks of code in curly braces (including blocks with only one statement). Consider the following code snippet:

int count1, count2, count3; if (count1 == 0) if (count2 == 0) if (count3 == 0) count1 = 1; else count2 = 1;

The question is: to which if does the else belong (do not be deceived by the indentations!)?

REVIEW EXERCISES

1. Your program needs to compute the gross weekly pay (double grossPay) for an employee given the employee's hourly wage (double hourlyWage), and the hours worked (double hours). If the hours worked is greater than 40, the extra hours are paid at "time-and-a-half". Write a code snippet to compute the gross weekly pay.

2. Your program needs to classify various HP printers by their model numbers (such as: HP Officejet 6500).

Why is the switch structure inadequate to do this? 3. Your program needs to classify the grass planted in several lots, according to a character variable (char

grassType), and the possible values for the type are: R (rye), F (fescue), B (Bermuda), Z (zoysia), P (pampas), or unknown. Write a code snippet using the switch structure that outputs the type of grass determined by the single character representing the grass type.

4. What is wrong with the following code snippet?

int count = 0; if (count = 0) count = 1;

STRING MANIPULATION

Besides just number-crunching, a lot of computer programs must manipulate characters and strings. In C++ the string is considered complex type (actually it is a class; classes are covered later). A character is considered a simple type.

Strings are derived from a C structure: the character array (arrays are also covered later). For now we will think of a string as a linear set of characters. The set has a first member, intermediate members, and a last member. All strings also have a length (which is an int).

Each character in the string has a position, i.e., the first, the second, and so on. In order to process strings effectively we often have to know the position of a character within a string. For this C++ uses a position marker, which is just another int. But, the first character is given position 0, the second position 1, and so on, up to position n-1, where n is the length of the string. If a string has spaces, tabs, newlines, or carriage returns in it, they each also have a (single) position.

In the following strings what is the position of the character 'a' and what is the length of the string?

"aardvark" - this string has an 'a' at positions 0, 1, and 5; its length is 8 "Havana" - this string has an 'a' at positions 1, 3, and 5; its length is 6 "America" - this string has an 'a' at position 6 only; its length is 7 "Have a nice day" - this string has an 'a' at positions 1, 5, and 13; its length is 15

It is very important to remember that the positions range from 0 to n-1 in a string of length n.

The end-of-line indicator in C++ is the newline: '\n'; back in the days that we used typewriters the end of a line was actually two characters: the carriage return and a newline. The carriage return placed the next character to type at the beginning of the current line, and the newline moved the next character to type to the next (blank) line.

Unfortunately, the three most common operating systems (OSs), MS Windows, Mac OS X, and UNIX, represent the end-of-line indicator differently in pure text files.

In MS Windows the end-of-line indicator is two characters: \r\n. In Mac OS X the end-of-line indicator is just: \r. In UNIX and its variants, the end-of-line indicator is just: \n.

Fortunately, the C++ compilers that exist today will (usually) deal with these differences seamlessly. That is, you usually do not have to worry about this difference in the text files that contain your programs. However, the different text editors that you may use to create other text files do not always deal with these differences seamlessly. Thus, if you move text files from one OS to another type, you may encounter this annoying difference.

STRING MANIPULATION OPERATORS AND FUNCTIONS

STRING MANIPULATION OPERATORS AND FUNCTIONS

The many string manipulations operators and function are declared in the include file <string>, which you must explicitly include in your program. We have already seen that strings can be compared with the comparison operators: ==, !=, <, >, <=, >=, which the ASCII-collating sequence defined by the ASCII character table.

Strings may be assigned to a variable using the assignment operator: =; strings may be appended to another string using the assignment operator: +=; and, strings can be concatenated using the operator: +.

string message = "Have a nice day!"; // initializes message message += " See you soon." // appends this string to message string newMessage = "I" + " love" + " you."

Various string functions are invoked using dot-notation: stringName.function( ).

string message = "An error occurred!"; int length = message.length(); // returns the length int size = message.size(); // so does this char whatIs = message.at(3); // returns 'e'

© 2011 cad18; rcm27; cpsm