My Implementation to C++ Primer (4th) Exercises (Chapter 2)

Exercise 2.1: What is the difference between an int, a long, and a short value?

The difference is by size, the number of bits used to represent the type, and number of bits vary from one machine with another, so there is no guarantee the exact bits of the built-in types.

Exercise 2.2: What is the difference between an unsigned and a signed type?

A signed type can represent both negative and positive numbers (including zero), whereas an unsigned type represent only values greater than or equal to zero.

Exercise 2.3: If a short on a given machine has 16 bits then what is the largest number that can be assigned to a short? To an unsigned short?

The largest number that can be assigned to a short would be 215-1 and for unsigned short would be 216-1.

Exercise 2.4: What value is assigned if we assign 100,000 to a 16-bit unsigned short? What value is assigned if we assigned 100,000 to a plain 16-bit short?

For 16-bit unsigned short, the largest number is 216-1, which less than 100,000 (out of range), so the value would be truncated to 100,000 mod 216 = 34464. Then plain 16-bit short is signed by default, largest number is 215-1 and smallest number is - 215 (out of range), so the value would be truncated to
(100,000 mod 215) + (-215) = -31072. (Note: The above results could only serve in Visual C++ Compiler (IA-32), other compilers aren't guaranteed the same results.)

Equations used:
(For more information please read Chapter 2 in [Computer Systems A Programmer's Perspective by Randal E. Bryant, David R. O'Hallaron])
B2Uk([xk-1,xk-2,...,x0]) = B2Uw([xk-1,xk-2,...,x0]) mod 2k -------------------------(1)
B2Tk([xk-1,xk-2,...,x0]) = U2Tk(B2Uw([xk-1,xk-2,...,x0]) mod 2k)-------------------(2)
U2Tw(x) = x (x < 2w-1) or U2Tw(x) = x - 2w (x >= 2w-1)--------------------------(3)
Note: For (1), (2) and (3), B stands for binary form, U stands for unsigned form, T stands for two's complement form and for the mod operation of (2)  is signed.
(1) unsigned w-bit number truncate to an unsigned k-bit number.
(2) unsigned w-bit number truncate to an unsigned k-bit number, then transform into two's complement form.
(3) unsigned form transform into two's complement form based on the range of x.

Exercise 2.5: What is the difference between a float and a double?

Typically, floats are represented in one word (32 bits), double in two words (64 bits). The size of the type determines the number of significant digits a floating-point value might contain.

Exercise 2.6: To calculate a mortgage payment, what types would you use for the rate, principal, and payment? Explain why you selected each type.

For the types for rate, principal and payment, I would consider using the double type for all. The reason is that three values usually contain decimal digits, which means that we can't use integer types. Another reason for choosing double instead of float is that float usually not precise enough, which would lead to wrong results if significant digits in the values exceed the float type.

Exercise 2.7: Explain the differences between the following sets of literal constants:
(a) 'a', L'a', "a", L"a"
(b) 10, 10u, 10L, 10uL, 012, 0xC
(c) 3.14, 3.14f, 3.14L

(a) 'a' represents a character literal with a single character a. L'a' represents a wide character literal with a single character a. "a" represents a character string literal which is an array of two characters with letter a and the null character. L"a" represents a wide string literal which is an array of two constant wide characters with a wide character a and a wide null character.
(b) 10 represents a literal integer constant, type is int. 10u represents a literal unsigned integer constant, type is unsigned int. 10L represents a literal integer constant, type is long. 10uL represents a literal unsigned integer constant, type is unsigned long. 012 represents a literal octal integer constants, type is int. 0xC represents a literal hexadecimal integer constant, type is int.
(c) 3.14 represents a floating-point literal, type is double. 3.14f represents a floating-point literal, type is float. 3.14L represents a floating-point literal, type is double.

Exercise 2.8: Determine the type of each these literal constants:
(a) 10
(b) 10u
(c) 10.
(d) 10e-2

(a) int
(b) unsigned int
(c) double
(d) double

Exercise 2.9: Which, if any, of the following are illegal?
(a) "Who goes with F\145rgus?\012"
(b) 3.14e1L
(c) "two" L"some"
(d) 1024f
(e) 3.14UL
(f) "multiple line
     comment"

(e), (c) and (f). Note: (c) is undefined, because it varies from one compiler to under another. (In Visual C++, this lead to mismatch type error.)

Exercise 2.10: Using escape sequences, write a program to print 2M followed by a newline. Modify the program to print 2, then a tab, then an M, followed by a newline.

#include <iostream>
 
int main()
{
    std::cout 
<< "2M\n";
    
return 0;
}

#include <iostream>
 
int main()
{
    std::cout 
<< "2" "\t" "M" "\n";
    
return 0;
}

Exercise 2.11: Write a program that prompts the user to input two numbers, the base and exponent. Print the result of raising the base to the power of the exponent.

#include <iostream>
 
int main()
{
    
int base, exponent;
    
if(std::cin >> base)
    
{
        
if(std::cin >> exponent)
        
{
            
int result = base;
            
for(int cnt = 0; cnt != exponent; ++cnt)
                result 
*= base;
            std::cout 
<< base << " raised to the power of "
                    
<< exponent << ": \t"
                    
<< result << std::endl;
        }

        
else
        
{
            std::cerr 
<< "Exponent can't be empty ?!" << std::endl;
            
return -1;
        }

    }

    
else
    
{
        std::cerr 
<< "Base can't be empty ?!" << std::endl;
        
return -1;
    }

    
return 0;
}

Exercise 2.12: Distinguish between an lvalue and an rvalue; show examples of each.

lvalue is an expression that is an value may appear as either the left-hand or right-hand side of an assignment.
rvalue is an expression that is an value may appear only on the right-hand side of an assignment.

Example of lvalue is variables and for rvalue is literals including integers, floating-points, characters and string.

Exercise 2.13: Name one case where a lvalue is required.

One condition is the assignment, which the left-operand must be lvalue.

Exercise 2.14: Which, if any, of the following names are invalid? Correct each identified invalid name.
(a) int double = 3.14159;
(b) char _;
(c) bool catch-22;
(d) char 1_or_2 = '1';
(e) float Float = 3.14f;

(a), (b) and (e) are valid.
(c) identifier name can be composed of letters, digits, and the underscore letter, so one way to correct is catch_22.
(d) identifier name must begin a letter or underscore, so one way to correct  is one_or_2.

Exercise 2.15: What, if any, are the differences between the following definitions:

int month = 9, day = 7;
int month = 09, day = 07;

If either definition contains an error, how might you correct the problem?

Corrections:
int month = 9, day = 7;
int month = 011, day = 07;

Exercise 2.16: Assuming calc is a function that returns a double, which, if any, of the following are illegal definitions? Correct any that are identified as illegal.
(a) int car = 1024, auto = 2048;
(b) int ival = ival;
(c) std::cin >> int input_value;
(d) double salary = wage = 9999.99;
(e) double calc = calc();

(a) correct.
(b) int ival2 = 0; int ival = ival2;
(c) int input_value; std::cin >> input_value;
(d) double wage; double salary = wage = 9999.99;
(e) double dcalc = calc();

Exercise 2.17: What are the initial values, if any of each of the following variables?

#include <string>

std::
string global_str;
int global_int;
 
int main()
{
    
int local_int;
    std::
string local_str;
    
// 
    return 0;
}

The value of global_str and local_str is an empty string. The value of global_int is 0. At last, the value of local_int is undefined, which is a garbage value within the type range.

Exercise 2.18: Explain the meaning of each of these instances of name:

1extern std::string name;
2std::string name("exercise 3.5a");
3extern std::string name("exercise 3.5a");

Line 1 is a declaration of name with type string.
Line 2 is a definition of name being initialized using direct-initialization.
Line 3 is a definition of name being initialized using direct-initialization, even it is labeled with extern, because it have an initializer.

Exercise 2.19: What is the value of j in the following program?

1int i = 42;
2 
3int main()
4{
5    int i = 100;
6    int j = i;
7    // 
8    return 0;
9}

The value of j is 100. The reason is that the i has local scope in main function which hides i outside the main function that has global scope, so j is assigned with the value of 100 which is the value of the local i.

Exercise 2.20: Given the following program fragment, what values are printed?

int i= 100, sum = 0;
for(int i = 0; i != 10++i)
    sum 
+= i;
std::cout 
<< i << " " << sum << std::endl;

The values printed are 100 and 45. The variable i in for header hides the variable i outside the for loop, so the sum being sumed the numbers from 0 to 9. Then at the output statement the variable i outside the for loop is visible again, which has value of 100.

Exercise 2.21: Is the following program legal?

int sum = 0;
for(int i = 0; i != 10++i)
    sum 
+= i;
std::cout 
<< "Sum from 0 to " << i
      
<< " is " << sum << std::endl;

The program is illegal, because the variable i in for header isn't visible outside the for loop.

Exercise 2.22: The following program fragment, while legal, is an example of  poor style. what problem(s) does it contain? How would you improve it?

for(int i = 0; i < 100++i)
    
//process i

The number of 100 means nothing in the for loop, we should assign a meaningful variable name for value 100 for readability and maintainability.

Exercise 2.23: Which of the following are legal? For those usages that are illegal, explain why.
(a) const int buf;
(b) int cnt = 0;
     const int sz = cnt;
(c) cnt++; sz++;

(a) illegal, the reason is that local const must be initialized, as value of const is unmodifiable if initialized first place then there no way to initialized afterwards.
(b) legal.
(c) illegal, sz is const so it is unmodifiable and cnt is legal as it is modifiable.

Exercise 2.24: Which of the following definitions, if any, are invalid? Why? How would you correct them?
(a) int ival = 1.01;
(b) int &rval1 = 1.01;
(c) int &rval2 = ival;
(d) const int &rval3 = 1;

(a) invalid, the type of ival is int, so to assign floating-point to int needs explicit casting.
(b) invalid, nonconst reference may be attached only to an object of the same type as the reference itself.
(c) valid.
(d) valid.

Exercise 2.25: Given the preceeding definitions, which, if any, of the following assignments are invalid? If they are valid, explain what they do.
(a) rval2 = 3.14159;
(b) rval2 = rval3;
(c) ival = rval3;
(d) rval3 = ival;

(a) invalid, assignment of different type require explicit casting.
(b) valid, assign value of rval3 to ival, as rval2 reference to ival. 
(c) valid, value of ival being assign with value of const reference rval3 which is 1.
(d) invalid, const reference is unmodifiable.

Exercise 2.26: What are the differences among the definitions in (a) and the assignments in (b)? Which, if any, are illegal?
(a) int ival = 0;
     const int &ri = 0;
(b) ival = ri;
     ri = ival;

The definitions in (a) is legal, but the second assignment in (b) is illegal, because const reference is unmodifiable.

Exercise 2.27: What does the following code print?

int i, &ri = i;
= 5; ri = 10;
std::cout 
<< i << " " << ri << std::endl;

The code print 10 10.

Exercise 2.28: Compile the following program to determine whether your compiler warns about a missing semicolon after a class definition:

class Foo
{
    
// empty
}
 // Note: no semicolon
int main()
{
    
return 0;
}

If the diagnostic is confusing, remember the message for future reference.

Yes, in Visual C++ Compiler shows us the message [error C2628: 'Foo' followed by 'int' is illegal (did you forget a ';'?)].

Exercise 2.29: Distinguish between the public and private sections of a class.

The public section of a class defines members that can be accessed by any part of the program. Code that is not part of the class does not have access to the private members.

Exercise 2.30: Define the data members of classes to represent the following types:
(a) a phone number
(b) an address
(c) an employee or a company
(d) a student at a university

(a): (based on international format)
class PhoneNo
{
    
int country_code;
    
long local_number;
    std::
string country;
}

(b): (based on China postal format)
class Address
{
    std::
string name;
    
int room_number;
    std::
string apartment_name;
    
int street_number;
    std::
string street_name;
    std::
string city;
    std::
string province;
    std::
string country;
    
int postcode;
}

(c): (an employee or a company)
class Employee
{
    std::
string fullname;
    std::
string gender;
    std::
string birthday;
    std::
string occupation;
    std::
string rank;
    std::
string working_company;
    std::
string working_department;
    Address living_addr;
    PhoneNo phone_no;
    
long employee_id;
}
;

class Company
{
    
int total_staffs;
    Address address;
    
int num_departments;
    Employee employee;
    PhoneNo contact_no;
}
;

(d):
class Student
{
    std::
string fullname;
    std::
string gender;
    std::
string birthday;
    Address address;
    PhoneNo phone_no;
    
int current_grade;
    
long student_no;
    std::
string major;
}

Exercise 2.31: Identify which of the following statements are declarations and which ones are definitions. Explain why they are declarations or definitions.
(a) extern int ix = 1024;
(b) int iy;
(c) extern int iz;
(d) extern const int &ri;

(a) is definition. The reason is that there is initializer in the statements, even though it is labeled with extern. 
(b), (c) and (d) are declarations. There are no initializers in these statements, the extern can be ignored so (b) is also a declaration. Their definitions are can be in different files.

Exercise 2.32: Which of the following declarations and definitions would you put in a header? In a source file? Explain why.
(a) int var;
(b) const double pi = 3.1416;
(c) extern int total = 255;
(d) const double sq2 = sqrt(2.0);

I would put (b) in header file, because it is a const is local to file by default and is initialized by a constant expression and they would probably be used in other sources files,  which other source files can include this header file to include these definitions. (a) and (c) is that if (a) and (b) are put in header file would lead to multiple definitions error, remind that when (a) and (b) are put in header is definitions not declarations ,so it should be include in source file, if we would want to share the variable then we should put a extern for that type in header file. (d) should be put in a source file, as the sqrt function is not called until runtime, so isn't a constant expression, if we would like the const used in other source files, then we can put an extern declaration for the const in header to be shared other source files.

posted on 2010-12-04 09:43 The A 阅读(2902) 评论(2)  编辑 收藏 引用 所属分类: C++

评论

# re: My Implementation to C++ Primer (4th) Exercises (Chapter 2) 2013-08-18 18:16 Dawogua


Exercise 2.31: Identify which of the following statements are declarations and which ones are definitions. Explain why they are declarations or definitions.
(a) extern int ix = 1024;
(b) int iy;
(c) extern int iz;
(d) extern const int &ri;

(a) is definition. The reason is that there is initializer in the statements, even though it is labeled with extern.
(b), (c) and (d) are declarations. There are no initializers in these statements, the extern can be ignored so (b) is also a declaration. Their definitions are can be in different files.
--------------------------------------------------------
有疑问,(b) 是 declaration or definition?
不管 int iy; 是在头文件,函数体外 还是函数体内, 都应该是definition。
内置类型在函数体外会被初始化为0;算是定义加初始化。
函数体内不会自动初始化,只算是定义。

不知道博主是不是误解了书中的这句话“Nonconst variable are extern by default. ” (chapter 2 , 2.4 const Qualifier 最后一个练习的上一行)
caoxianghan@gmail.com  回复  更多评论   

# re: My Implementation to C++ Primer (4th) Exercise (Chapter 2.11) 2015-06-22 22:41 海狸

错误

锻炼;
2.11

CNT = 0
必须是
CNT = 1  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2015年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜