Q10. Use enum to define a type called Response with the possible values Yes, No, and Maybe. Yes should be 1, No should be 0, and Maybe should be 2.
A:
enum Response {Yes = 1, No = 0, Maybe = 2};
Q11. Suppose ted is a double variable. Declare a pointer that points to ted and use the pointer to diplay ted's value.
A:
double * bd = & ted;
cout << *bd << "\n";
Q12.Suppose treacle is an array of 10 floats. Declare a pointer that points to the first element of of treacle and use the pointer to display the first and last elements of the
array.
A:
float * pf = &treacle[0];
cout << pf[0] << " " << pf[9] << "\n";
Q13. Write a code fragment that asks the user to enter a positive integer and then creates a dynamic array of that many ints. Do this by using new, then again using a
vector object.
A:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
<pre name="code" class="cpp"> unsigned int size;
cout << "Enter a positive integer: "; cin >> size; int * dyn = new int[size]; vector<int> dv(size); return 0;}
Q14. Is the following valid? If so, what does it print?
cout << (int *) "Home of the jolly bytes";
A: Yes, it is valid. The expession "Home of the jolly bytes" is a string constant; hence it evaluates as the address of the beginning of the string. The cout object inter-
prets the address of a char as an invitation to print a string, but the type cast (int *) converts the address to type pointer-to-int, which is then printed as an address.
In short, the statement prints the address of the string, assuming the int type is wide enough to hold an address.
Q15. Write a code fragment that dynamically allocates a structure of the type described in Question 8 and the reads a value for the kind member of the structure.
A:
struct fish
{
char king[20];
int weight;
float length;
};
fish * pole = new fish;
cout << "Enter kind of fish: ";
cin >> pole->kind;
Q16. Listing 4.6 illustrates a problem created by following numeric input with line-oriented string input. How would replacing this:
cin.getline(address, 80);
with this:
cin >> address;
affect the working of this program?
A: Using cin >> address causes a program to skip over whitespace until it finds non-whitespace. It then reads characters until it encounters whitespace again. Thus,
it will skip over the newline following the numeric input, avoiding that problem. On the other hand, it will read just a single word, not an entire line.
Q17. Decare a vector object of 10 string objects and an array object of 10 string objects. Show the necessary header files and don't use using. Do use a const for
the number of strings.
A:
#include <iostream>
#include <vector>
#include <array>
const int Str_num {10}; // or = 10
...
std::vector<std::string> vstr(Str_num);
std::array<std::string, Str_num>astr;