Answers to Exercises

1.3c43. In case you got a different result, here's a little help:
  1. If you got the result 433a, you started at the wrong address.

  2. If you got the result 433c, you had the bytes reversed.

  3. Finally, if you got 3a43, you made both of these mistakes.

If you made one or more of these mistakes, don't feel too bad; even experienced programmers have trouble with hexadecimal values once in awhile. That's one reason we use compilers and assemblers rather than writing everything in hex!

2.“HELLO”. If you couldn't figure out what the “D” at the beginning was for, you started at the wrong place.
3.Figure 3.25 is Susan's answer to this problem.
Figure 3.25. First dinner party program (codeasic05.cpp)
#include <iostream>
using namespace std;

int main()
{
    short n;

    cout << "Please type in the number of guests ";
    cout << "of your dinner party. ";
    cin >> n;

    cout << "A table for " << n+1 << "is ready. ";

    return 0;
}

By the way, the reason that this program uses two lines to produce the sentence “Please type in the number of guests of your dinner party.” is so that the program listing will fit on the page properly. If you prefer, you can combine those into one line that says:

cout << "Please type in the number of guests of your dinner party. ";.

Of course, this also applies to the next exercise. Here's the discussion that Susan and I had about this exercise:

Susan: I would have sent it sooner had I not had the last cout arrows going like this >> (details).<G> Also, it just didn't like the use of endl; at the end of the last cout statement. It just kept saying “parse error”.

Steve: If you wrote something like

cout  <<  "A table for "  << n+1 <<  "is ready. " << "endl;"

then it wouldn't work for two reasons. First, "endl;" is just a character string, not anything recognized by <<. Second, you're missing a closing ;, because characters inside quotes are treated as just plain characters by the compiler, not as having any effect on program structure.

The correct way to use endl in your second output statement is as follows:

cout << "A table for " << n+1 << "is ready. " << endl;

By the way, you might want to add a " " in front of the is in is ready, so that the number doesn't run up against the is. That would make the line look like this:

cout << "A table for " << n+1 << " is ready. " << endl;

Susan: Okay.

4.Figure 3.26 is Susan's answer to this problem, followed by our discussion.
Figure 3.26. Second dinner party program (codeasic06.cpp)
#include <iostream>
using namespace std;

int main()
{
    short n;

    cout << "Excluding yourself, please type the ";
    cout << "number of guests in your dinner party.
";

    cin >> n;

    if (n>20)
        cout << "Sorry, your party is too large. ";
    else
        cout << "A table for " << n+1 << " is ready. ";

    return 0;
}

Steve: Congratulations on getting your program to work!

Susan: Now, let me ask you this: can you ever modify else? That is, could I have written else (n>20)?

Steve: You can say something like what is shown in Figure 3.27.

Figure 3.27. else if example
if (x < y)
  {
  cout << "x is less than y" << endl;
  }
else
    {
    if (x > y)
      cout << "x is greater than y" << endl;
    else
      cout << "x must be equal to y!" << endl;
    }

In other words, the controlled block of an if statement, or an else statement, can have another if or else inside it. In fact, you can have as many “nested” if or else statements as you wish; however, it's best to avoid very deep nesting because it tends to confuse the next programmer who has to read the program.

5.The answer to this problem should look like Figure 3.28.
Figure 3.28. Name and age program (codeasic07.cpp)
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string name;
    short age;

    cout << "What is your first name? ";
    cin >> name;

    cout << "Thank you, " << name << endl;

    cout << "What is your age? ";
    cin >> age;

    if (age < 53)
        cout << "My, what a youngster!" << endl;
    else
      cout << "That is very old, " << name << ". " << endl;

    return 0;
}

One point that might be a bit puzzling in this program is why it's not necessary to add an << endl to the end of the lines that send data to cout before we ask the user for input. For example, in the sequence:

cout << "What is your first name? ";
cin >> name;

how do we know that the C string literal "What is your first name? " has been displayed on the terminal before the user has to type in the answer? Obviously, it would be hard for the user to answer our request for information without a clue as to what we're asking for.

As it happens, this is a common enough situation that the designers of the iostream library have anticipated it and solved it for us. When we use that library to do output to the screen and then request input from the keyboard, we can be sure that any screen output we have already requested will be displayed before any input is requested from the user via the keyboard.

That wasn't the only subtle point that this problem raised. You'll be happy (or at least unsurprised) to hear that Susan and I had quite a discussion about this problem and its solution:

Susan: When I was trying to put that period in the answer, I finally got it to work with double quotes. But then I thought that maybe it should have been surrounded by single quotes ' instead of double quotes. It worked with a double quote but since it was only one character it should have been a single quote, so I went back and changed it to a single quote and the compiler didn't like that at all. So I put it back to the double. So what is the deal?

Steve: You should be able to use 'x' or "x" more or less interchangeably with <<, because it can handle both of those data types (char and C string literal, respectively). However, they are indeed different types. The first one specifies a literal char value, whereas the second specifies a C string literal value. A char value can only contain one character, but a C string literal can be as long as you want, from none to hundreds or thousands of characters.

Susan: Here's the line that gave me the trouble:

cout << "That is very old, " << name << ". " << endl;

Remember I wanted to put that period in at the end in that last line? It runs like this but not with the single quotes around it. That I don't understand. This should have been an error. But I did something right by mistake <G>. Anyway, is there something special about the way a period is handled?

Steve: I understand your problem now. No, it's not the period; it's the space after the period. Here are four possible versions of that line:

  1. cout << "That is very old, " << name << ". " << endl;

  2. cout << "That is very old, " << name << '. ' << endl;

  3. cout << "That is very old, " << name << "." << endl;

  4. cout << "That is very old, " << name << '.' << endl;

None of these is exactly the same as any of the others. However, 1, 3, and 4 will do what you expect, whereas 2 will produce weird looking output, with some bizarre number where the "." should be. Why is this? It's not because "." is handled specially, but because the space (" "), when inside quotes, either single or double, is a character like any other character. Thus, the expression '. ' in line 2 is a “multicharacter constant”, which has a value dependent on the compiler; with the compiler on the CD, you'll get a short value equal to (256 * the ASCII value of the period) + the ASCII value of the space. This comes out to 11808, as I calculate it. So the line you see on the screen may look like this:

That is very old, Joe11808

Now why do all of the other lines work? Well, 1 works because a C string literal can have any number of characters and be sent to cout correctly; 3 works for the same reason; and 4 works because '.' is a valid one-character constant, which is another type that << can handle.

I realize it's hard to think of the space as a character when it doesn't look like anything; in addition, you can add spaces freely between variables, expressions, and so forth, in the program text. However, once you're dealing with C string literals and literal character values, the space is just like any other character.

Susan: So it is okay to use single characters in double quotes? If so, why bother with single quotes?

Steve: Single quotes surround a literal of type char. This is a 1-byte value that can be thought of (and even used) as a very short number. Double quotes surround a literal value of type “C string literal”. This is a multibyte value terminated by a 0 byte, which cannot be used or treated as a number.

Susan: I am not too clear on what exactly the difference is between the char and “C string literal”. I thought a char was like an alpha letter, and a string was just a bunch of letters.

Steve: Right. The difference is that a C string literal is variable length, and a char isn't; this makes a lot of difference in how they can be manipulated.

Susan: Am I right in thinking that a char could also be a small number that is not being used for calculations?

Steve: Or that is used for (very small) calculations; for instance, if you add 1 to the value 'A', you get the value for 'B'. At least that's logical.

Susan: What do you mean by “terminated by a 0 byte”? That sounds familiar; was that something from an earlier chapter which is now ancient history?

Steve: Yes, we covered that some time ago. The way the program can tell that it's at the end of a C string literal (which is of variable length, remember) is that it gets to a byte with the value 0. This wouldn't be my preferred way to specify the size of a variable-length string, but it's too late to do anything about it; it's built into the compiler.

Susan: When you say a C string literal, do you mean the C programming language in contrast to other languages?

Steve: Yes.

Susan: All right, then the 0 byte used to terminate a C string literal is the same thing as a null byte?

Steve: Yes.

Susan: Then you mean that each C string literal must end in a 0 so that the compiler will know when to stop processing the data for the string?

Steve: Yes.

Susan: Could you also just put 0? Hey, it doesn't hurt to ask. I don't see the problem with the word hello; it ends with an o and not a 0. But what if you do need to end the sentence with a 0?

Steve: It's not the digit '0', which has the ASCII code 30h, but a byte with a 0 value. You can't type in a null byte directly, although you can create one with a special character sequence if you want to. However, there's no point in doing that usually, because all C string literals such as "hello" always have an invisible 0 byte added automatically by the compiler. If for some reason you need to explicitly create a null byte, you can write it as '', as in

char x = '';

which emphasizes that you really mean a null byte and not just a plain old 0 like this:

char x = 0;

The difference between these two is solely for the benefit of the next programmer who looks at your code; they're exactly the same to the compiler.

6.Figure 3.29 shows Susan's program, which is followed by our discussion.
Figure 3.29. Novice program (codeasic08.cpp)
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string answer;

    cout << "Please respond to the following statement ";
    cout << "with either true or false
";

    cout << "Susan is the world's most tenacious novice.
";
    cin >> answer;

    if (answer != "true")
        if (answer != "false")
            cout << "Please answer with either true or false.";

    if (answer == "true")
        cout << "Your answer is correct
";

    if (answer == "false")
        cout << "Your answer is erroneous
";

    return 0;
}

Susan: Steve, look at this. It even runs!

Also, I wanted to ask you one more question about this program. I wanted to put double quotes around the words true and false in the 3rd output statement because I wanted to emphasize those words, but I didn't know if the compiler could deal with that so I left it out. Would that have worked if I had?

Steve: Not if you just added quotes, because " is a special character that means “beginning or end of C string literal”. Here's what you would have to do to make it work:

cout << "Please answer with either "true" or "false".";

The is a way of telling the compiler to treat the next character differently from its normal usage. In this case, we are telling the compiler to treat the special character " as “not special”; that is, " means “just the character double quote, please, and no nonsense”. This is called an escape sequence, because it allows you to get out of the trap of having a " mean something special. We also use the to tell the compiler to treat a “nonspecial” character as “special”; for example, we use it to make up special characters that don't have any visual representation. You've already seen ' ', the “newline” character, which means “start a new line on the screen”.

Susan: So if we want to write some character that means something “special”, then we have to use a in front of it to tell the compiler to treat it like a “regular” character?

Steve: Right.

Susan: And if we want to write some character that is “regular” and make it do something “special”, then we have to use a in front of it to tell the compiler that it means something “special”?

Steve: Yes, that's the way it works.

Susan: I now just got it. I was going to say, why would you put the first quotation mark before the slash in ' ', but now I see. Since you are doing an endline character, you have to have quotes on both sides to surround it which you don't usually have to do because the first quotes are usually started at the beginning of the sentence, and in this case the quote was already ended.

Steve: You've got it.

Susan: Another thing I forgot is how you refer to the code in () next to the “if” keywords; what do you call that?

Steve: The condition.

7.Figure 3.30 is Susan's version of this program. Actually, it was her idea in the first place.
Figure 3.30. Allowance program (codeasic09.cpp)
#include <iostream>
using namespace std;

int main()
{
    short x;

    cout << "Elena can increase her $10 allowance each week ";
    cout << "by adding new chores." << endl;

    cout << "For every extra chore Elena does, she gets ";
    cout << "another dollar." << endl;
    cout << "How many extra chores were done? " << endl;
    cin >> x;

    if (x==0)
        {
        cout << "There is no extra allowance for Elena ";
        cout << "this week. " << endl;
        }
    else
        {
        cout << "Elena will now earn " << 10 + x;
        cout << " dollars this week." << endl;
        }

    return 0;
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset