Tải bản đầy đủ (.pdf) (20 trang)

C++ Primer Plus (P15) pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (772.25 KB, 20 trang )

Suppose you want to print all the array contents. Then, you can use one for loop to change
rows and a second, nested for loop to change columns:
for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 5; col++)
cout << maxtemps[row][col] << "\ t";
cout << "\n";
}
For each value of row, the inner for loop cycles through all the col values. This example
prints a tab character (\t in C++ notation) after each value and a newline character after
each complete row.
Initializing a Two-Dimensional Array
When you create a two-dimensional array, you have the option of initializing each element.
The technique is based on that for initializing a one-dimensional array. That method, you
remember, is to provide a comma-separated list of values enclosed in braces:
// initializing a one-dimensional array
int btus[5] = { 23, 26, 24, 31, 28};
For a two-dimensional array, each element is itself an array, so you can initialize each
element by using a form like that in the previous code example. Thus, the initialization
consists of a comma-separated series of one-dimensional initializations all enclosed in a
set of braces:
int maxtemps[4][5] = // 2-D array
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
{
{94, 98, 87, 103, 101} , // values for maxtemps[0]
{98, 99, 91, 107, 105} , // values for maxtemps[1]
{93, 91, 90, 101, 104} , // values for maxtemps[2]
{95, 100, 88, 105, 103} // values for maxtemps[3]
};
The term {94, 98, 87, 103, 101} initializes the first row, represented by maxtemps[0]. As
a matter of style, placing each row of data on its own line, if possible, makes the data


easier to read.
Listing 5.19 incorporates an initialized two-dimensional array and a nested loop into a
program. This time the program reverses the order of the loops, placing the column loop
(city index) on the outside and the row loop (year index) on the inside. Also, it uses a
common C++ practice of initializing an array of pointers to a set of string constants. That is,
cities is declared as an array of pointers-to-char. That makes each element, such as
cities[0], a pointer-to-char that can be initialized to the address of a string. The program
initializes cities[0] to the address of the "Gribble City" string, and so on. Thus, this array
of pointers behaves like an array of strings.
Listing 5.19 nested.cpp
// nested.cpp nested loops and 2-D array
#include <iostream>
using namespace std;
const int Cities = 5;
const int Years = 4;
int main()
{
const char * cities[Cities] = // array of pointers
{ // to 5 strings
"Gribble City",
"Gribbletown",
"New Gribble",
"San Gribble",
"Gribble Vista"
};
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
int maxtemps[Years][Cities] = // 2-D array
{
{95, 99, 86, 100, 104} , // values for maxtemps[0]
{95, 97, 90, 106, 102} , // values for maxtemps[1]

{96, 100, 940, 107, 105} , // values for maxtemps[2]
{97, 102, 89, 108, 104} // values for maxtemps[3]
};
cout << "Maximum temperatures for 1999 - 2002\n\n";
for (int city = 0; city < Cities; city++)
{
cout << cities[city] << ":\ t";
for (int year = 0; year < Years; year++)
cout << maxtemps[year][city] << "\ t";
cout << "\n";
}
return 0;
}
Here is the program output:
Maximum temperatures for 1999 - 2002
Gribble City: 95 95 96 97
Gribbletown: 99 97 100 102
New Gribble: 86 90 940 89
San Gribble: 100 106 107 108
Gribble Vista: 104 102 105 104
Using tabs in the output spaces the data more regularly than using spaces would.
However, different tab settings can cause the output to vary in appearance from one
system to another. Chapter 17 presents more precise, but more complex, methods for
formatting output.
Summary
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
C++ offers three varieties of loops: the for loop, the while loop, and the do while loop. A
loop cycles through the same set of instructions repetitively as long as the loop test
condition evaluates to true or nonzero, and the loop terminates execution when the test
condition evaluates to false or zero. The for loop and the while loop are entry-condition

loops, meaning they examine the test condition before executing the statements in the
body of the loop. The do while loop is an exit-condition loop, meaning it examines the test
condition after executing the statements in the body of the loop.
The syntax for each loop calls for the loop body to consist of a single statement. However,
that statement can be a compound statement, or block, formed by enclosing several
statements within paired curly braces.
Relational expressions, which compare two values, are often used as loop test conditions.
Relational expressions are formed by using one of the six relational operators: <, <=, ==,
>=, >, or !=. Relational expressions evaluate to the type bool values true and false.
Many programs read text input or text files character-by-character. The istream class
provides several ways to do this. If ch is a type char variable, the statement
cin >> ch;
reads the next input character into ch. However, it skips over spaces, newlines, and tabs.
The member function call
cin.get(ch);
reads the next input character, regardless of its value, and places it in ch. The member
function call cin.get() returns the next input character, including spaces, newlines, and
tabs, so it can be used as follows:
ch = cin.get();
The cin.get(char) member function call reports encountering the end-of-file condition by
returning a value with the bool conversion of false, whereas the cin.get() member function
call reports end-of-file by returning the value EOF, which is defined in the iostream file.
A nested loop is a loop within a loop. Nested loops provide a natural way to process
two-dimensional arrays.
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
Review Questions
.1:What's the difference between an entry-condition loop and an exit-condition
loop? Which kind is each of the C++ loops?
.2:What would the following code fragment print if it were part of a valid program?
int i;

for (i = 0; i < 5; i++)
cout << i;
cout << "\n";
.3:What would the following code fragment print if it were part of a valid program?
int j;
for (j = 0; j < 11; j += 3)
cout << j;
cout << "\n" << j << "\n";
.4:What would the following code fragment print if it were part of a valid program?
int j = 5;
while ( ++j < 9)
cout << j++ << "\n";
.5:What would the following code fragment print if it were part of a valid program?
int k = 8;
do
cout <<" k = " << k << "\n";
while (k++ < 5);
.6:Write a for loop that prints the values 1 2 4 8 16 32 64 by increasing the value
of a counting variable by a factor of 2 each cycle.
.7:How do you make a loop body include more than one statement?
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
.8:Is the following statement valid? If not, why not? If so, what does it do?
int x = (1,024);
What about the following?
int y;
y = 1,024;
.9:How does cin>>ch differ from cin.get(ch) and ch=cin.get() in how it views
input?
Programming Exercises
1:Write a program that requests the user to enter two integers. The program then

should calculate and report the sum of all the integers between and including the
two integers. At this point, assume that the smaller integer is entered first. For
example, if the user enters 2 and 9, the program reports that the sum of all the
integers from 2 through 9 is 44.
2:Write a program that asks you to type in numbers. After each entry, the number
reports the cumulative sum of the entries to date. The program terminates when
you enter a zero.
3:Daphne invests $100 at 10% simple interest. That is, every year, the investment
earns 10% of the original investment, or $10 each and every year:
interest = 0.10 x original balance
At the same time, Cleo invests $100 at 5% compound interest. That is, interest
is 5% of the current balance, including previous additions of interest:
interest = 0.05 x current balance
Cleo earns 5% of $100 the first year, giving her $105. The next year she earns
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
5% of $105, or $5.25, and so on. Write a program that finds how many years it
takes for the value of Cleo's investment to exceed the value of Daphne's
investment and then displays the value of both investments at that time.
4:
You sell C++ For Fools. Write a program that has you enter a year's worth of
monthly sales (in terms of number of books, not of money). The program should
use a loop to prompt you by month, using an array of char * initialized to the
month strings and storing the input data in an array of int. Then, the program
should find the sum of the array contents and report the total sales for the year.
5:Do Programming Exercise 4 but use a two-dimensional array to store input for
three years of monthly sales. Report the total sales for each individual year and
for the combined years.
6:Design a structure called car that holds the following information about an
automobile: its make as a string in a character array and the year it was built as
an integer. Write a program that asks the user how many cars to catalog. The

program then should use new to create a dynamic array of that many car
structures. Next, it should prompt the user to input the make (which might
consist of more than one word) and year information for each structure. Note
that this requires some care, for it alternates reading strings with numeric data
(see Chapter 4). Finally, it should display the contents of each structure. A
sample run should look something like the following:
How many cars do you wish to catalog? 2
Car #1:
Please enter the make: Hudson Hornet
Please enter the year made: 1952
Car #2:
Please enter the make: Kaiser
Please enter the year made: 1951
Here is your collection:
1952 Hudson Hornet
1951 Kaiser
7:Write a program using nested loops that asks the user to enter a value for the
number of rows to display. It then displays that many rows of asterisks, with one
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
asterisk in the first row, two in the second row, and so on. For each row, the
asterisks are preceded by the number of periods needed to make all the rows
display a total number of characters equal to the number of rows. A sample run
would look like this:
Enter number of rows: 5
*
**
***
.****
*****
CONTENTS

This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
CONTENTS
Chapter 6. BRANCHING STATEMENTS AND
LOGICAL OPERATORS
In this chapter you learn
The if Statement
Logical Expressions
The cctype Library of Character Functions
The ?: Operator
The switch Statement
The break and continue Statements
Number-Reading Loops
Summary
Review Questions
Programming Exercises
One of the keys to designing intelligent programs is to give them the ability to make
decisions. Chapter 5, "Loops and Relational Expressions," shows you one kind of decision
making—looping—in which a program decides whether or not to continue looping. Now
you investigate how C++ lets you use branching statements to decide among alternative
actions. Which vampire-protection scheme (garlic or cross) should the program use? What
menu choice has the user selected? Did the user enter a zero? C++ provides the if and
switch statements to implement decisions, and they are this chapter's main topics. You
also look at the conditional operator, which provides another way to make a choice, and
the logical operators, which let you combine two tests into one.
The if Statement
When a C++ program must choose whether or not to take a particular action, you usually
implement the choice with an if statement. The if comes in two forms: if and if else. Let's
investigate the simple if first. It's modeled after ordinary English, as in "If you have a
Captain Cookie card, you get a free cookie." The if statement directs a program to execute
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.

a statement or statement block if a test condition is true and to skip that statement or block
if the condition is false. Thus, an if statement lets a program decide whether a particular
statement should be executed.
The syntax is similar to the while syntax:
if (test-condition)
statement
A true test-condition causes the program to execute statement, which can be a single
statement or a block. A false test-condition causes the program to skip statement. (See
Figure 6.1.) As with loop test conditions, an if test condition is typecast to a bool value, so
zero becomes false and nonzero becomes true. The entire if construction counts as a
single statement.
Figure 6.1. The if statement.
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
Most often, test-condition is a relational expression such as those used to control loops.
Suppose, for example, you want a program that counts the spaces in the input as well as
the total number of characters. You can use cin.get(char) in a while loop to read the
characters and then use an if statement to identify and count the space characters. Listing
6.1 does just that, using the period to recognize the end of a sentence.
Listing 6.1 if.cpp
// if.cpp using the if statement
#include <iostream>
using namespace std;
int main()
{
char ch;
int spaces = 0;
int total = 0;
cin.get(ch);
while (ch != '.') // quit at end of sentence
{

if (ch == ' ') // check if ch is a space
spaces++;
total++; // done every time
cin.get(ch);
}
cout << spaces << " spaces, " << total;
cout << " characters total in sentence\n";
return 0;
}
Here's some sample output:
The balloonist was an airhead
with lofty goals.
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
6 spaces, 46 characters total in sentence
As the comments indicate, the spaces++; statement is executed only when ch is a space.
Because it is outside the if statement, the total++; statement is executed every loop cycle.
Note that the total count includes the newline character generated by pressing Enter.
The if else Statement
While the if statement lets a program decide whether a particular statement or block is
executed, the if else statement lets a program decide which of two statements or blocks is
executed. It's an invaluable statement for creating alternative courses of action. The C++ if
else is modeled after simple English, as in "If you have a Captain Cookie card, you get a
Cookie Plus Plus, else you just get a Cookie d'Ordinaire." The if else statement has this
general form:
if (test-condition)
statement1
else
statement2
If test-condition is true or nonzero, the program executes statement1 and skips over
statement2. Otherwise, when test-condition is false or zero, the program skips

statement1 and executes statement2 instead. So the code fragment
if (answer == 1492)
cout << "That's right!\n";
else
cout << "You'd better review Chapter 1 again.\n";
prints the first message if answer is 1492 and prints the second message otherwise. Each
statement can be either a single statement or a statement block delimited by braces. (See
Figure 6.2.) The entire if else construct counts syntactically as a single statement.
Figure 6.2. The if else statement.
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
For example, suppose you want to alter incoming text by scrambling the letters while
keeping the newline character intact. That way, each line of input is converted to an output
line of equal length. This means you want the program to take one course of action for
newline characters and a different course of action for all other characters. As Listing 6.2
shows, if else makes this task easy.
Listing 6.2 ifelse.cpp
// ifelse.cpp using the if else statement
#include <iostream>
using namespace std;
int main()
{
char ch;
cout << "Type, and I shall repeat.\n";
cin.get(ch);
while (ch != '.')
{
if (ch == '\n')
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
cout << ch; // done if newline
else

cout << ++ch; // done otherwise
cin.get(ch);
}
// try ch + 1 instead of ++ch for interesting effect
cout << "\nPlease excuse the slight confusion.\n";
return 0;
}
Here's some sample output:
Type, and I shall repeat.
I am extraordinarily pleased
J!bn!fyusbpsejobsjmz!qmfbtfe
to use such a powerful computer.
up!vtf!tvdi!b!qpxfsgvm!dpnqvufs
Please excuse the slight confusion.
Note that one of the program comments suggests that changing ++ch to ch+1 has an
interesting effect. Can you deduce what it will be? If not, try it out and then see if you can
explain what's happening. (Hint: Think about how cout handles different types.)
Formatting Your if else Statements
Keep in mind that the two if else alternatives must be single statements. If you need more
than one statement, use braces to collect them into a single block statement. Unlike some
languages, such as BASIC or FORTRAN, C++ does not automatically consider everything
between if and else a block, so you have to use braces to make the statements a block.
The following code, for example, produces a compiler error. The compiler sees it as a
simple if statement that ends with the zorro++; statement. Then there is a cout statement.
So far, so good. But then there is what the compiler perceives as an unattached else, and
that is flagged as a syntax error.
if (ch == 'Z')
zorro++; // if ends here
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
cout << "Another Zorro candidate\n";

else // wrong
dull++;
cout << "Not a Zorro candidate\n";
Add the braces to convert the code to what you want:
if (ch == 'Z')
{ // if true block
zorro++;
cout << "Another Zorro candidate\n";
}
else
{ // if false block
dull++;
cout << "Not a Zorro candidate\n";
}
Because C++ is a free-form language, you can arrange the braces as you like, as long as
they enclose the statements. The preceding code shows one popular format. Here's
another:
if (ch == 'Z') {
zorro++;
cout << "Another Zorro candidate\n";
}
else {
dull++;
cout << "Not a Zorro candidate\n";
}
The first form emphasizes the block structure for the statements, whereas the second form
more closely ties the blocks to the keywords if and else. Either style is clear and consistent
and should serve you well; however, you may encounter an instructor or employer with
strong and specific views on the matter.
The if else if else Construction

This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
Computer programs, like life, might present you with a choice of more than two selections.
You can extend the C++ if else statement to meet that need. The else, you've seen,
should be followed by a single statement, which can be a block. Because an if else
statement itself is a single statement, it can follow an else:
if (ch == 'A')
a_grade++; // alternative # 1
else
if (ch == 'B') // alternative # 2
b_grade++; // subalternative # 2a
else
soso++; // subalternative # 2b
If ch is not 'A', the program goes to the else. There, a second if else subdivides that
alternative into two more choices. C++'s free formatting enables you to arrange these
elements into an easier-to-read format:
if (ch == 'A')
a_grade++; // alternative # 1
else if (ch == 'B')
b_grade++; // alternative # 2
else
soso++; // alternative # 3
This looks like a new control structure—an if else if else structure. But actually it is one if
else contained within a second. This revised format looks much cleaner, and it enables you
to skim through the code to pick out the different alternatives. This entire construction still
counts as one statement.
Listing 6.3 uses this preferred formatting to construct a modest quiz program.
Listing 6.3 ifelseif.cpp
// ifelseif.cpp using if else if else
#include <iostream>
using namespace std;

const int Fave = 27;
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
int main()
{
int n;
cout << "Enter a number in the range 1-100 to find ";
cout << "my favorite number: ";
do
{
cin >> n;
if (n < Fave)
cout << "Too low guess again: ";
else if (n > Fave)
cout << "Too high guess again: ";
else
cout << Fave << " is right!\n";
} while (n != Fave);
return 0;
}
Here's some sample output:
Enter a number in the range 1-100 to find my favorite number: 50
Too high guess again: 25
Too low guess again: 37
Too high guess again: 31
Too high guess again: 28
Too high guess again: 27
27 is right!
Real World Note: Conditional Operators and Bug Prevention
Many programmers reverse the more intuitive expression
variable == value to value == variable in order to catch

errors where the equality is mistyped as an assignment
operator. For example, entering the conditional as
if (3 == myNumber)
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
is valid and will work properly. However, if you happen to
mistype
if (3 = myNumber)
the compiler will generate an error message, as it believes
you are attempting to assign a value to a literal (3 always
equals 3, and can't be assigned another value). Suppose
you made a similar mistake made using the former
notation:
if (myNumber = 3)
The compiler will simply assign the value 3 to myNumber,
and the block within the if will run— a very common error,
and a difficult error to find. As a general rule, writing code
that allows the compiler to find errors is much easier than
repairing the causes of mysterious faulty results.
Logical Expressions
Often you must test for more than one condition. For example, for a character to be a
lowercase letter, its value must be greater than or equal to 'a' and less than or equal to 'z'.
Or, if you ask a user to respond with a y or an n, you want to accept uppercase (Y and N)
as well as lowercase. To meet this kind of need, C++ provides three logical operators to
combine or modify existing expressions. The operators are logical OR, written ||; logical
AND, written &&; and logical NOT, written !. Examine them now.
The Logical OR Operator: ||
In English, the word or can indicate when one or both of two conditions satisfy a
requirement. For example, you can go to the MegaMicro company picnic if you or your
spouse work for MegaMicro, Inc. The C++ equivalent is the logical OR operator, written ||.
This operator combines two expressions into one. If either or both of the original

expressions are true, or nonzero, the resulting expression has the value true. Otherwise
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
the expression has the value false. Here are some examples:
5 ==5 || 5 == 9 // true because first expression is true
5 > 3 || 5 > 10 // true because first expression is true
5 > 8 || 5 < 10 // true because second expression is true
5 < 8 || 5 > 2 // true because both expressions are true
5 > 8 || 5 < 2 // false because both expressions are false
Because the || has a lower precedence than the relational operators, you don't need to use
parentheses in these expressions. Table 6.1 summarizes how the || operator works.
C++ provides that the || operator is a sequence point. That is, any value changes
indicated in the left side take place before the right side is evaluated. For example,
consider the following expression:
i++ < 6 || i == j
Suppose i originally has the value 10. By the time the comparison with j takes place, i has
the value 11. Also, C++ won't bother evaluating the expression on the right if the
expression on the left is true, for it only takes one true expression to make the whole logical
expression true. (The semicolon and the comma operator also are sequence points.)
Listing 6.4 uses the || operator in an if statement to check for both uppercase and
lowercase versions of a character. Also, it uses C++'s string concatenation feature (see
Chapter 4, "Compound Types") to spread a single string over three lines.
Table 6.1. The || Operator
The Value of expr1 || expr2

expr1 == trueexpr1 == false
expr2 == truetruetrue
expr2 == falsetruefalse
Listing 6.4 or.cpp
// or.cpp use logical OR operator
#include <iostream>

This document was created by an unregistered ChmMagic, please go to to register it. Thanks.
using namespace std;
int main()
{
cout << "This program may reformat your hard disk\n"
"and destroy all your data.\n"
"Do you wish to continue? <y/n> ";
char ch;
cin >> ch;
if (ch == 'y' || ch == 'Y') // y or Y
cout << "You were warned!\a\a\n";
else if (ch == 'n' || ch == 'N') // n or N
cout << "A wise choice bye\n";
else
cout << "That wasn't a y or an n, so I guess I'll "
"trash your disk anyway.\n";
return 0;
}
Here is a sample run:
This program may reformat your hard disk
and destroy all your data.
Do you wish to continue? <y/n> N
A wise choice bye
The program reads just one character, so only the first character in the response matters.
That means the user could have replied NO! instead of N. The program would just read the
N. But if the program tried to read more input later, it would start at the O.
The Logical AND Operator: &&
The logical AND operator, written &&, also combines two expressions into one. The
resulting expression has the value true only if both of the original expressions are true.
Here are some examples:

5 == 5 && 4 == 4 // true because both expressions are true
This document was created by an unregistered ChmMagic, please go to to register it. Thanks.

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×