Answer to practice questions

directory

| – section 1.1 practice

| – section 1.2 practice

| – section 1.3 practice

| – section 1.4 practice

| – section 1.5 practice

| – section 1.6 practice


Section 1.1 practice

Exercise 1.1: Consult your compiler’s documentation to determine the file naming convention it uses. Compile and run the main program on page 2.

Answer:

G++ 5.4.0 is used.

C c source file file.h C header file (preprocessed file) file. I Preprocessed C source file file.cc ++ source file file.cc C++ source file file. CXX C++ source file file.m Objective-c source file file.s Assembly language file file.o Target file a.out Connection output fileCopy the code

Echo $? 0.

Exercise 1.2: Rewrite the program so that it returns -1. The return value -1 is usually taken as an indication of a program error. Recompile and run your program, and watch how your system handles the error flags returned by Main.

Answer:

Echo $? Echo $? The output of 255


Section 1.2 practice

Exercise 1.3: Write a program to print Hello, World on standard output.

Answer:

#include <iostream>

int main(a)
{
    std: :cout<<"Hello, World";
    return 0;
}
Copy the code

Exercise 1.4: Our program uses the addition operator + to add two numbers. Write a program to print the product of two numbers using the multiplication operator *.

Answer:

#include <iostream>
int main(a)
{
    std: :cout << "Enter two numbers:" << std: :endl;
    int v1 = 0, v2 = 0;
    std: :cin >> v1 >> v2;
    std: :cout << "The product of " << v1 <<" and " << v2
              << " is " << v1 * v2 << std: :endl;
    return 0;
}
Copy the code

Exercise 1.5: We put all the output operations in one long statement. Rewrite the program to place each operand print operation in a separate statement.

Answer:

#include <iostream>
int main(a)
{
    std: :cout << "Enter two numbers:" << std: :endl;
    int v1 = 0, v2 = 0;
    std: :cin >> v1 >> v2;
    
/* * std::cout << "The product of " << v1 <<" and " << v2 * << " is " << v1 * v2 << std::endl; * /

    std: :cout << "The product of ";
    std: :cout << v1;
    std: :cout << " and ";
    std: :cout << v2;
    std: :cout << " is ";
    std: :cout << v1 * v2;
    std: :cout << std: :endl;
    return 0;
}
Copy the code

Exercise 1.6: Explain whether the following program fragment is legal.

std: :cout << "The sum of " << v1;
          << " and " << v2;
          << " is " << v1 + v2 << std: :endl;

Copy the code

If the program is legal, what does it output? If the procedure is illegal, why? How should it be fixed?

Answer:


Section 1.3 practice

Exercise 1.7: Compile a program that contains incorrect nested comments and watch for error messages returned by the compiler.

Answer:

/* Nested comments /* */* /int main(a)
{
   return 0;
}
Copy the code

Exercise 1.8: Indicate which of the following output statements, if any, are legal:

std::cout << "/*";
std::cout << "*/";
std::cout << /* "*/" */
std::cout << /* "*/" /* "/*" */;
Copy the code

Answer:

Predict actual STD ::cout << "/*"; STD ::cout << "*/"; STD ::cout << /* "*/" */; STD ::cout << /*" */" /*" /*" /*" */; Right and wrongCopy the code

Rewrite the third statement as

// Add two /*
std: :cout << / * * / "* /" / * * /;
// Or add a quotation mark
std: :cout << / * * /" */";
Copy the code


Section 1.4.1 practice

Exercise 1.9: Write a program to add integers from 50 to 100 using a while loop.

Answer:

int main(a)
{
    int sum = 0;
    int n = 50;
    while (n <= 100) {
        sum += n;
        n++;
    }
    return 0;
}
Copy the code

Exercise 1.10In addition to the ++ operator, which increments the value of an operand by 1, there is also a decrement operator (–) that decays the value by 1. Write a program to print integers between 10 and 0 in descending order in a loop using the decrement operator.

Answer:

#include <iostream>
int main(a)
{
    int n = 10;
    while (n >= 0) {
        std: :cout << n << std: :endl;
        n--;
    }
    return 0;
}

Copy the code

Exercise 1.11: Write a program that prompts the user for two integers and prints all integers in the range specified by these two integers.

Answer:

#include <iostream>
int main(a)
{
    int low, high;
    std: :cout << "Enter two numbers:" << std: :endl;
    std: :cin >> low >> high;
    if (low > high) {
        int temp = low;
        low = high;
        high = temp;
    }
    while (low <= high) {
        std: :cout << low << std: :endl;
        low++;
    }
    return 0;
}
Copy the code


Section 1.4.2 practice

Exercise 1.12: What does the following for loop accomplish? What is the final value of sum?

int sum = 0;
for (int i = - 100.; i <= 100; ++i)
    sum += i;
Copy the code

Answer:

Sum is the sum from -100 to 100, and sum ends at 0. .

Exercise 1.13: Repeat all the exercises in Section 1.4.1 using the for loop.

Answer:

/ / 1.9
int main
{
    int sum = 0;
    for (int i = 50; i <= 100; ++i) {
        sum += i;
    }
    return 0;
}


/ / 1.10
#include <iostream>
int main
{
    for (int i = 10; i >= 0; --i) {
        std: :cout << i << std: :endl;
    }
    return 0;
}


/ / 1.11
#include <iostream>
int main(a)
{
    std: :cout << "Enter two numbers:" << std: :endl;
    int low, high;
    std: :cin >> low >> high;
    if (low > high) {
        int temp = low;
        low = high;
        high = temp;
    }
    for (; low <= high; ++low) {
        std: :cout << low << std: :endl;
    }
    return 0;
}
Copy the code

Exercise 1.14: Comparing the for loop with the while loop, what are the pros and cons of each?

Answer:

Exercise 1.15: Write a program that contains the common errors discussed in “Exploratory Compilation” on page 14. Be familiar with error messages generated by the compiler.


Section 1.4.3 practice

Exercise 1.16: Write a program to read a set of numbers from CIN and print their sum.

Answer:

#include <iostream>
int main(a)
{
    int num;
    int sum = 0;
    while (std: :cin >> num) {  // Check STD :: CIN status
        sum += num;
    }
    std: :cout << sum << std: :endl;
    return 0;
}
Copy the code

Enter the end of file from the keyboard:

1. On Windows, Enter the end of file by Ctrl+Z and press Enter or Return. 2. On Unix, including Mac OS X, end-of-file input is Ctrl+D.


Section 1.4.4 practice

Exercise 1.17: What does this program output if all input values are equal? What happens to the output if there are no duplicate values?

Answer:

The program runs correctly. As shown in figure:

Note: if you input different data, the program will output immediately. If you input all the same data, the program will output only when it encounters the end-of-file symbol.

Exercise 1.18: Compile and run this program, giving it all equal values. Run the program again and enter no duplicate values.

Answer:

#include <iostream>
int main(a)
{
    int currVal = 0, val = 0;
    if (std: :cin >> currVal) {
        int cnt = 1;
        while (std: :cin >> val) {
            if (currVal == val) {
	        cnt++;
	    } else {
	        std: :cout << currVal << " occurs "
                          << cnt << " times" << std: :endl;
		cnt = 1; currVal = val; }}std: :cout << currVal << " occurs "
                  << cnt << " times" << std: :endl;
    } else {
        std: :cerr << "No data? !" << std: :endl;
        return - 1;
    }
    return 0;
}
Copy the code

Exercise 1.19: Completed, the code written in Exercise 1.10 in Section 1.4.1 can handle this situation. Click the jump


Section 1.5.1 practice

You can download the source code based on the compiler you use.

Practice: 1.20 in the website www.informit.com/title/03217… The code directory in Chapter 1 contains the sales_item.h header file. Copy it to your own working directory. Use it to write a program that reads a set of book sales records and prints each record to the standard output stream.

Answer:

Compiling with g++ requires specifying the c++ standard with the argument -std=c++11, otherwise an error will be reported. Cp [option] source dest Copies the file from source to dest.

#include <iostream>
#include "Sales_item.h"
int main(a)
{
    Sales_item book;
    std: :cin >> book;
    std: :cout << book << std: :endl;
    return 0;
}
Copy the code

Use file redirection by reading a file for input, not the keyboard, and by output to a file instead of the screen. $./prog < inputFile > outputFile > redirects the standard output stream. If it is a file, it overwrites the contents of the original file. >> also repositions the standard output stream, not overwriting the original file content but adding new content after the original file content.

Exercise 1.21: Write a program that reads two Sales_item objects with the same ISBN and prints their sum.

Answer:

#include <iostream>
#include "Sales_item.h"
int main(a)
{
    Sales_item book1, book2;
    std: :cin >> book1 >> book2;
    if (book1.isbn() == book2.isbn()) {
      std: :cout << book1 + book2 << std: :endl;
    } else {
      std: :cerr << "Different ISBN" << std: :endl;
    }
    return 0;
}
Copy the code

Exercise 1.22: Write a program that reads multiple sales records with the same ISBN and prints the sum of all records.

Answer:

The input must have the same ISBN sales record.

#include <iostream>
#include "Sales_item.h"
int main(a)
{
    Sales_item total; // The variable that holds the next transaction record
    // Read the first record and make sure there is data to process
    if (std: :cin >> total) {
        Sales_item trans;     // Save the and variable
        // Read and process the remaining transaction records
        while (std: :cin >> trans) {
                total += trans;
        }
        // All records processed, start writing
        std: :cout << total << std: :endl;
    } else {
        // No input!
        std: :cerr << "No data? !" << std: :endl;
        return - 1;  // Indicates that the program failed to run
    }
    return 0;
}
Copy the code


Section 1.5.2 practice

Exercise 1.23: Write a program to read multiple sales records and count how many sales records there are per ISBN (per book).

Answer:

#include <iostream>
#include "Sales_item.h"
int main(a)
{
    Sales_item total; // The variable that holds the next transaction record
    // Read the first record and make sure there is data to process
    if (std: :cin >> total) {
        Sales_item trans;     // Save the and variable
        // Read and process the remaining transaction records
        while (std: :cin >> trans) {
            // If we are still dealing with the same ISBN book
	    if (total.isbn() == trans.isbn()) {
                total += trans; // Update total sales
	    } else {
                // Prints the results of the previous book
                std: :cout << total << std: :endl; total = trans; }}// When all records are processed, print the last book result
        std: :cout << total << std: :endl;
        
    } else {
        // No input!
        std: :cerr << "No data? !" << std: :endl;
        return - 1;  // Indicates that the program failed to run
    }
    return 0;
}
Copy the code

Exercise 1.24: Test the previous program by entering multiple sales records representing multiple ISBNs, the records for each ISBN program should be clustered together.

Answer:


Section 1.6 practice

Exercise 1.25: Compile and run the bookstore program presented in this section using the Sales_item.h header file from the web site.

Answer:

The bookstore program is the same as exercise 1.23, running as exercise 1.24.


Summary of Core Knowledge points

(1) every C++ program contains one or more functions, one of which must be named main. The operating system calls main to run C++ programs.

(2) On most systems, the return value from main is used to indicate the status. A return value of 0 indicates success, while a non-0 return value has a system-defined meaning and is usually used to indicate error types

(3) Type is one of the most basic concepts of programming. A type defines not only the contents of data elements, but also the operations that can be performed on such data.

(4) The iostream library includes two basic types, istream and ostream, representing input and output streams respectively. A stream is a sequence of characters read or written from an IO device. “Stream” means that characters are generated or consumed sequentially over time. Cin is an object for istream, cout and cerr and CLOG are objects for ostream.

In object-oriented thinking, a type can be thought of as a class type, that is, istream and Ostream are two classes, while CIN and cout are instance objects of classes.

(5) When a stream object is used as a condition, its effect is to detect the state of the stream. If the flow is valid, that is, the flow encounters no errors, the detection succeeds. The state of the stream object becomes invalid when an end-of-file is encountered or when an invalid input is encountered. An object in an invalid state makes the condition false.


English terminology learning session

Only pick what I think is important and common!

Argument (argument) : argument

Assignment: the assignment

Built-in type: built-in-type

Class: class

Note: the comment

Curly brace

Data structure: Data structure

End-of-file (EOF)

Expression: expression

Function: the function

Initialization: Initialize

Standard Library: Standard Library

Operator: manipulator

Namespace: namespace

Statement: the statement

Operator: operator

Variables: variable

String constants: string literal

Sentence: refs parameter

Give it a thumbs up if you think it’s useful! Let me keep doing it.