Google
 

Monday, January 10, 2011

C++ Primer, Fourth Edition-Notes:Chapter 5. Exercises

Exercise 5.1:

// Exercise 5.1.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
/*
Parenthesize the following expression to indicate how it is evaluated. Test your answer by compiling the expression and printing its result.
12 / 3 * 4 + 5 * 15 + 24 % 4 / 2
*/

cout << "12 / 3 * 4 + 5 * 15 + 24 % 4 / 2 = " << 12 / 3 * 4 + 5 * 15 + 24 % 4 / 2 <<endl;
// (12 / 3 * 4) + (5 * 15) + (24 % 4 / 2)
// 16 + 75 + 0 = 91
return 0;
}

Exercise 5.1 result


Exercise 5.2:

// Exercise 5.2.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
/*
Determine the result of the following expressions and indicate which results, if any, are machine-dependent.
-30 * 3 + 21 / 5
-30 + 3 * 21 / 5
30 / 3 * 21 % 5
-30 / 3 * 21 % 4
*/

cout << "-30 * 3 + 21 / 5 = " << -30 * 3 + 21 / 5 << endl; // no machine-dependent
cout << "-30 + 3 * 21 / 5 = " << -30 + 3 * 21 / 5 << endl; // no machine-dependent
cout << "30 / 3 * 21 % 5 = " << 30 / 3 * 21 % 5 << endl; // no machine-dependent
cout << "-30 / 3 * 21 % 4 = " << -30 / 3 * 21 % 4 << endl; // machine-dependent
return 0;
}

Exercise 5.2 result


 


Exercise 5.3:

// Exercise 5.3.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
//Write an expression to determine whether an int value is even or odd.
cout << "Write an expression to determine whether an int value is even or odd." << endl;
cout << "Please input your integer:" << endl;
int input(0);
while(cin >> input)
{
if(0 == input % 2)
{
cout << "You number:" << input << " is even!" << endl;
}
else
{
cout << "You number:" << input << " is odd!" << endl;
}
cout << "\nPlease input an integer:" << endl;
}
return 0;
}
Exercise 5.3 result 

Exercise 5.4:




// Exercise 5.4.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
//Define the term overflow. Show three expressions that will overflow.
char a = 0xFFFF;
cout << "char a = 257; a = " << a << endl;
unsigned int b = 0xFFFFFFFF;
int c = b;
cout << "unsigned int b = 0xFFFFFFFF;int c = b; c = " << c << endl;

unsigned short d = 0xFFFF;short e = d;
cout << "unsigned short d = 0xFFFF;short e = d; e = " << e << endl;

return 0;
}

Exercise 5.4 result


Exercise 5.5:


Exercise 5.6:

// Exercise 5.6.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

int main()
{
/*
Explain the behavior of the following while condition:
char *cp = "Hello World";
while (cp && *cp)
*/

char *cp = "Hello World";

while (cp && *cp)
{
cout << *cp << endl;
++cp;
}
return 0;
}
Exercise 5.6 result 

Exercise 5.7:

// Exercise 5.7.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

int main()
{
/*
Write the condition for a while loop that would read ints from the standard input and stop when the value read is equal to 42.
*/

cout << "Please input integers (terminate with 42):" << endl;
int input(0);
vector<int> pool;
while( cin >> input)
{
if( 42 == input )
{
cout << "Terminate the input loop!" << endl;
break;
}
pool.push_back(input);
}
cout << "Your input are:" << endl;
for (vector<int>::iterator begin = pool.begin();
begin != pool.end(); ++begin)
{
cout << *begin << endl;
}

return 0;
}
Exercise 5.7 result 

Exercise 5.8:


// Exercise 5.8.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{
/*
Write an expression that tests four values, a, b, c, and d, and ensures that a is greater than b, which is greater than c, which is greater than d.
*/

int a(1),b(2),c(3),d(4);
//int a(4),b(3),c(2),d(1);
if((a > b) && (b > c) && (c > d))
{
cout << "if((a > b) && (b > c) && (c > d)) is true!" << endl;
}
else
{
cout << "if((a > b) && (b > c) && (c > d)) is false!" << endl;
}
return 0;
}
Exercise 5.8 result 

Exercise 5.9:

// Exercise 5.9.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
//#include <string>
using namespace std;

int main()
{
/*
Assume the following two definitions:
unsigned long ul1 = 3, ul2 = 7;
What is the result of each of the following expressions?
(a) ul1 & ul2 (c) ul1 | ul2
(b) ul1 && ul2 (d) ul1 || ul2
*/

unsigned long ul1 = 3, ul2 = 7;
cout << "ul1 & ul2 :" << ( ul1 & ul2 ) << endl;
cout << "ul1 && ul2 :" << ( ul1 && ul2 ) << endl;
cout << "ul1 | ul2 :" << (ul1 | ul2) << endl;
cout << "ul1 || ul2 :" << (ul1 || ul2) << endl;
return 0;
}
Exercise 5.9 result 

Exercise 5.10:

// Exercise 5.10.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <bitset>
using namespace std;
int main()
{
/*Rewrite the bitset expressions that set and reset the quiz results using a subscript operator.
*/

bitset<30> quiz1;
//set
quiz1[27] = 1;
cout << "quiz1[27] = 1; quiz1 = " << quiz1 << endl;
//reset
quiz1[27] = 0;
cout << "quiz1[27] = 0; quiz1 = " << quiz1 << endl;

return 0;
}

Exercise 5.10 result




Exercise 5.11:

What are the values of i and d after the each assignment:

     int i;   double d;
d = i = 3.5;
i = d = 3.5;
	int i;   double d;
d = i = 3.5;
// i is 3, d is 3;
cout << i << " " << d << endl;
i = d = 3.5;
cout << i << " " << d << endl;
// d is 3.5, i is 3;


Exercise 5.12:

Explain what happens in each of the if tests:

     if (42 = i)   // . . .
if (i = 42) // . . .
    if (42 = i)   // . . .
// error , can assign value to non-lvalue
if (i = 42) // . . .
// always returns true

Exercise 5.13:

The following assignment is illegal. Why? How would you correct it?

     double dval; int ival; int *pi;
dval = ival = pi = 0;

 

	double dval; int ival1; int *pi;
dval = ival1 = pi = 0;
// different type;

Exercise 5.14:

Although the following are legal, they probably do not behave as the programmer expects. Why? Rewrite the expressions as you think they should be.

     (a) if (ptr = retrieve_pointer() != 0)
(b) if (ival = 1024)
(c) ival += ival + 1;
	if (ptr = retrieve_pointer() != 0)
{}
if ((ptr = retrieve_pointer() )!= 0)
{}
if (ival = 1024)
{}
if (ival == 1024)
{}

ival += ival + 1;
ival += 1;
ival = ival + 1;


Exercise 5.15:

Explain the difference between prefix and postfix increment.

Exercise 5.16:

Why do you think C++ wasn't named ++C?

Exercise 5.17:

What would happen if the while loop that prints the contents of a vector used the prefix increment operator?

	iter = ivec.begin();
// prints 10 9 8 ... 1
while (iter != ivec.end())
cout << *(++iter) << endl; // iterator postfix increment

Exception:


+        message    0x01089ad8 "vector iterator not dereferencable"    const wchar_t *

image

 

Exercise 5.18:

Write a program that defines a vector of pointers to strings. Read the vector, printing each string and its corresponding size.

// Exercise 5.18.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, _TCHAR* argv[])
{
vector<string*> vect;
cout << "Please input 5 strings:" << endl;
int i = 5;
string str[5];
while(i-- != 0)
{
cin >> str[i];
vect.push_back(&str[i]);
}

cout << &str << str << endl;

vector<string*>::iterator iter = vect.begin();
while(iter!= vect.end())
{
cout << **iter << " size:"<< (*iter)->size() << endl;
iter++;
}
cin >> i;
return 0;
}

Exercise 5.19:

Assuming that iter is a vector<string>::iterator, indicate which, if any, of the following expressions is legal. Explain the behavior of the legal expressions.

     (a) *iter++;         (b) (*iter)++;
(c) *iter.empty() (d) iter->empty();
(e) ++*iter; (f) iter++->empty();
// Exercise 5.19.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, _TCHAR* argv[])
{
//(a) *iter++; (b) (*iter)++;
//(c) *iter.empty() (d) iter->empty();
//(e) ++*iter; (f) iter++->empty();

vector<string> vect;
int i = 2;
string str[5];
while(i-- != 0)
{
cin >> str[i];
vect.push_back(str[i]);
}

vector<string>::iterator iter = vect.begin();
while(iter != vect.end())
{
//(a) *iter++;
// access the iter pointed item value and increase the iterator;
//cout << *iter++ << endl;
//(b) (*iter)++;
// access the iter pointed item value and increase the iterator;
//(*iter)++;
//(c) *iter.empty()
// error , can use (*iter).empty();
// call string's empty method
//cout << (*iter).empty() << endl;
//(d) iter->empty();
// call vector's empty method
//cout << iter->empty() << endl;
//(e) ++*iter;
// error, increase the vector's item value
//++*iter;
//(f) iter++->empty();
// call iteratored item's empty method, and increase the iterator
cout << iter++->empty() << endl;
cout << *iter << endl;
iter++;
}
cin >> i;

return 0;
}


Exercise 5.20:

Write a program to prompt the user for a pair of numbers and report which is smaller.

// Exercises 5.7.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>

#include <string>
#include <iostream>

using namespace std;

int main(int argc, _TCHAR* argv[])
{
//Write a program to prompt the user for a pair of numbers and report which is smaller.

cout << "Please input two numbers:" << endl;
int a;
cin >> a;
int b;
cin >> b;
cout << "Smaller is " << (a < b ? a : b ) << endl;

cin >> a;
return 0;
}

Exercise 5.21:

Write a program to process the elements of a vector<int>. Replace each element with an odd value by twice that value.

// Exercise 5.21.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main(int argc, _TCHAR* argv[])
{
vector<int> vect;
cout << "Please input integers:" << endl;

int i = -1;
while( i != 0)
{
cin >> i;
vect.push_back(i);
}
// double element value
vector<int>::iterator iter = vect.begin();
while(iter != vect.end())
{
*iter++ *= 2;
}
iter = vect.begin();
while(iter != vect.end())
{
cout << *iter++ << endl;
}

cin >> i;
return 0;
}

Exercise 5.22:

Write a program to print the size of each of the built-in types.

// Exercise 5.22.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

int main(int argc, _TCHAR* argv[])
{
// bool
// boolean
// NA
cout << "bool type size is " << sizeof(bool) << endl;

// char
// character
// 8 bits
cout << "char type size is " << sizeof(char) << endl;

// wchar_t
// wide character
// 16 bits
cout << "wchar_t type size is " << sizeof(wchar_t) << endl;

// short
// short integer
// 16 bits
cout << "short type size is " << sizeof(short) << endl;

// int
// integer
// 16 bits
cout << "int type size is " << sizeof(int) << endl;

// long
// long integer
// 32 bits
cout << "long type size is " << sizeof(long) << endl;

// float
// single-precision floating-point
// 6 significant digits
cout << "float type size is " << sizeof(float) << endl;

// double
// double-precision floating-point
// 10 significant digits
cout << "double type size is " << sizeof(double) << endl;

// long double
// extended-precision floating-point
// 10 significant digits
cout << "long type size is " << sizeof(long) << endl;

int i;
cin >> i;
return 0;
}

Exercise 5.23:

Predict the output of the following program and explain your reasoning. Now run the program. Is the output what you expected? If not, figure out why.

     int x[10];   int *p = x;
cout << sizeof(x)/sizeof(*x) << endl;
cout << sizeof(p)/sizeof(*p) << endl;
// Exercise 5.23.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

int main(int argc, _TCHAR* argv[])
{
//Predict the output of the following program and explain your reasoning. Now run the program. Is the output what you expected? If not, figure out why.

int x[10]; int *p = x;

cout << p << endl;
cout << x << endl;
cout << *p << endl;
cout << x[0] << endl;
// 40/4;
cout << sizeof(x)/sizeof(*x) << endl;
//4/4
cout << sizeof(p)/sizeof(*p) << endl;

int i;
cin >> i;

return 0;
}

Exercise 5.24:

The program in this section is similar to the program on page 163 that added elements to a vector. Both programs decremented a counter to generate the element values. In this program we used the prefix decrement and the earlier one used postfix. Explain why we used prefix in one and postfix in the other.

// Exercise 5.24.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>

using namespace std;

int main (int argc, _TCHAR* argv[])
{
//The program in this section is similar to the program on page 163 that added elements to a vector. Both programs decremented a counter to generate the element values. In this program we used the prefix decrement and the earlier one used postfix. Explain why we used prefix in one and postfix in the other.

vector<int> ivec; // empty vector
int cnt = 100;
// add elements 10...1 to ivec
while (cnt > 0)
ivec.push_back(--cnt); // int postfix decrement

vector<int>::iterator iter = ivec. begin();
while(iter != ivec.end())
cout << *iter++ << endl;

int i;
cin >> i;

return 0;
}

Exercise 5.28:

With the exception of the logical AND and OR, the order of evaluation of the binary operators is left undefined to permit the compiler freedom to provide an optimal implementation. The trade-off is between an efficient implementation and a potential pitfall in the use of the language by the programmer. Do you consider that an acceptable trade-off? Why or why not?

?

Exercise 5.29:

Given that ptr points to a class with an int member named ival, vec is a vector holding ints, and that ival, jval, and kval are also ints, explain the behavior of each of these expressions. Which, if any, are likely to be incorrect? Why? How might each be corrected?

     (a) ptr->ival != 0            (b) ival != jval < kval
(c) ptr != 0 && *ptr++ (d) ival++ && ival
(e) vec[ival++] <= vec[ival]

Exercise 5.30:

Which of the following, if any, are illegal or in error?

     (a) vector<string> svec(10);
(b) vector<string> *pvec1 = new vector<string>(10);
(c) vector<string> **pvec2 = new vector<string>[10];
(d) vector<string> *pv1 = &svec;
(e) vector<string> *pv2 = pvec1;

(f) delete svec;
(g) delete pvec1;
(h) delete [] pvec2;
(i) delete pv1;
(j) delete pv2;
// Exercise 5.30.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main(int argc, _TCHAR* argv[])
{
//Which of the following, if any, are illegal or in error?
//(a) vector<string> svec(10);
vector<string> svec(10);
//(b) vector<string> *pvec1 = new vector<string>(10);
vector<string> *pvec1 = new vector<string>(10);
//(c) vector<string> **pvec2 = new vector<string>[10];
//vector<string> **pvec2 = new vector<string>[10];
//error: not valid deffinition
//(d) vector<string> *pv1 = &svec;
vector<string> *pv1 = &svec;
//(e) vector<string> *pv2 = pvec1;
vector<string> *pv2 = pvec1;
//(f) delete svec;
//delete svec;
//error: can delete undamically deffinition
//(g) delete pvec1;
delete pvec1;
//(h) delete [] pvec2;
//delete [] pvec2;
//error: delete syntax is not valid
//(i) delete pv1;
//delete pv1;
//error: can delete undamically deffinition
//(j) delete pv2;
//delete pv2;
//error: can delete the same address's pointers twice.a

int i;
cin >> i;
return 0;
}

Exercise 5.31:

Given the variable definitions on page 180, explain what conversions take place when evaluating the following expressions:

     (a) if (fval)
(b) dval = fval + ival;
(c) dval + ival + cval;


Exercise 5.32:

Given the following set of definitions,

     char cval;  int ival;   unsigned int ui;
float fval; double dval;

identify the implicit type conversions, if any, taking place:

     (a) cval = 'a' + 3;        (b) fval = ui - ival * 1.0;
(c) dval = ui * fval; (d) cval = ival + fval + dval;

Exercise 5.33:

Given the following set of definitions,

     int ival;                         double dval;
const string *ps; char *pc; void *pv;

rewrite each of the following using a named cast notation:

     (a) pv = (void*)ps;     (b) ival = int(*pc);
(c) pv = &dval; (d) pc = (char*) pv;

No comments: