Читаем C++ Primer Plus полностью

1. Both versions give the same answers, but the if else version is more efficient. Consider what happens, for example, when ch is a space. Version 1, after incrementing spaces, tests whether the character is a newline. This wastes time because the program has already established that ch is a space and hence could not be a newline. Version 2, in the same situation, skips the newline test.

2. Both ++ch and ch + 1 have the same numerical value. But ++ch is type char and prints as a character, while ch + 1, because it adds a char to an int, is type int and prints as a number.

3. Because the program uses ch = '$' instead of ch == '$', the combined input and output looks like this:

Hi!

H$i$!$

$Send $10 or $20 now!

S$e$n$d$ $ct1 = 9, ct2 = 9

Each character is converted to the $ character before being printed the second time. Also the value of the expression ch = $ is the code for the $ character, hence nonzero, hence true; so ct2 is incremented each time.

4.

a. weight >= 115 && weight < 125

b. ch == 'q' || ch == 'Q'

c. x % 2 == 0 && x != 26

d. x % 2 == 0 && !(x % 26 == 0)

e. donation >= 1000 && donation <= 2000 || guest == 1

f. (ch >= 'a' && ch <= 'z') ||(ch >= 'A' && ch <= 'Z')

5. Not necessarily. For example, if x is 10, then !x is 0 and !!x is 1. However, if x is a bool variable, then !!x is x.

6. (x < 0)? -x : x

or

(x >= 0)? x : -x;

7.

switch (ch)

{

    case 'A': a_grade++;

              break;

    case 'B': b_grade++;

              break;

    case 'C': c_grade++;

              break;

    case 'D': d_grade++;

              break;

    default:  f_grade++;

              break;

}

8. If you use integer labels and the user types a noninteger such as q, the program hangs because integer input can’t process a character. But if you use character labels and the user types an integer such as 5, character input will process 5 as a character. Then the default part of the switch can suggest entering another character.

9. Here is one version:

int line = 0;

char ch;

while (cin.get(ch) && ch != 'Q')

{

    if (ch == '\n')

        line++;

}

Answers to Chapter Review for Chapter 7

1. The three steps are defining the function, providing a prototype, and calling the function.

2.

a. void igor(void); // or void igor()

b. float tofu(int n); // or float tofu(int);

c. double mpg(double miles, double gallons);

d. long summation(long harray[], int size);

e. double doctor(const char * str);

f. void ofcourse(boss dude);

g. char * plot(map *pmap);

3.

void set_array(int arr[], int size, int value)

{

    for (int i = 0; i < size; i++)

        arr[i] = value;

}

4.

void set_array(int * begin, int * end, int value)

{

    for (int * pt = begin; pt != end; pt++)

        pt* = value;

}

5.

double biggest (const double foot[], int size)

{

    double max;

    if (size < 1)

    {

        cout << "Invalid array size of " << size << endl;

        cout << "Returning a value of 0\n";

        return 0;

    }

    else    // not necessary because return terminates program

    {

        max = foot[0];

        for (int i = 1; i < size; i++)

            if (foot[i] > max)

                max = foot[i];

        return max;

    }

}

6. You use the const qualifier with pointers to protect the original pointed-to data from being altered. When a program passes a fundamental type such as an int or a double, it passes it by value so that the function works with a copy. Thus, the original data is already protected.

7. A string can be stored in a char array, it can be represented by a string constant in double quotation marks, and it can be represented by a pointer pointing to the first character of a string.

8.

int replace(char * str, char c1, char c2)

{

    int count = 0;

    while (*str)      // while not at end of string

    {

        if (*str == c1)

        {

            *str = c2;

            count++;

        }

        str++;        // advance to next character

    }

    return count;

}

9. Because C++ interprets "pizza" as the address of its first element, applying the * operator yields the value of that first element, which is the character p. Because C++ interprets "taco" as the address of its first element, it interprets "taco"[2] as the value of the element two positions down the line—that is, as the character c. In other words, the string constant acts the same as an array name.

10. To pass it by value, you just pass the structure name glitz. To pass its address, you use the address operator &glitz. Passing by the value automatically protects the original data, but it takes time and memory. Passing by address saves time and memory but doesn’t protect the original data unless you use the const modifier for the function parameter. Also passing by value means you can use ordinary structure member notation, but passing a pointer means you have to remember to use the indirect membership operator.

11. int judge (int (*pf)(const char *));

12.

a. Note that if ap is an applicant structure, then ap.credit_ratings is an array name and ap.credit_ratings[i] is an array element.

void display(applicant ap)

{

    cout << ap.name << endl;

    for (int i = 0; i < 3; i++)

        cout  << ap.credit_ratings[i] <<  endl;

}

b. Note that if pa is a pointer to an applicant structure, then pa->credit_ratings is an array name and pa->credit_ratings[i] is an array element.

void show(const applicant * pa)

{

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных