EXPLORATION 3

image

Integer Expressions

In Exploration 2, you examined a program that defined a few variables and performed some simple operations on them. This Exploration introduces the basic arithmetic operators. Read Listing 3-1, then answer the questions that follow it.

Listing 3-1.  Integer Arithmetic

 1 /// Read the program and determine what the program does.
 2
 3 #include <iostream>
 4
 5 int main()
 6 {
 7     int sum{0};
 8     int count{};
 9     int x;
10     while (std::cin >> x)
11     {
12         sum = sum + x;
13         count = count + 1;
14     }
15
16     std::cout << "average = " << sum / count << ' ';
17 }

What does the program in Listing 3-1 do?

_____________________________________________________________

_____________________________________________________________

Test the program with the following input:

10   50   20   40   30

Lines 7 and 8 initialize the variables sum and count to zero. You can enter any integer value in the curly braces to initialize a variable (line 7); the value does not have to be constant. You can even leave the curly braces empty to initialize the variable to a suitable default value (e.g., false for bool, 0 for int), as shown on line 8. Without any curly braces, the variable is not initialized, so the only action the program can do is to assign a new value to the variable, as shown on lines 9 and 10. Ordinarily, it’s a bad idea not to initialize your variables, but in this case, x is safe, because line 10 immediately stuffs a value into it by reading from the standard input.

Lines 12 and 13 show examples of addition (+) and assignment (=). Addition follows the normal rules of computer arithmetic (we’ll worry about overflow later). Assignment works the way it does in any procedural language.

Thus, you can see that Listing 3-1 reads integers from the standard input, adds them up, and prints the average (mean) value, as computed by the division (/) operator. Or does it?

What is wrong with Listing 3-1?

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Try running the program with no input—that is, press the end-of-file keystroke immediately after starting the program. Some operating systems have a “null” file that you can supply as the input stream. When a program reads from the null file, the input stream always sees an end-of-file condition. On UNIX-like operating systems, run the following command line:

list0301 < /dev/null

On Windows, the null file is called NUL, so type

list0301 < NUL

What happens?

_____________________________________________________________

C++ doesn’t like division by zero, does it? Each platform reacts differently. Most systems indicate an error condition one way or another. A few quietly give you garbage results. Either way, you don’t get anything meaningful.

Fix the program by introducing an if statement. Don’t worry that the book hasn’t covered if statements yet. I’m confident you can figure out how to ensure this program avoids dividing by zero. Write the corrected program below:

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Now try your new program. Was your fix successful?

_____________________________________________________________

Compare your solution with Listing 3-2.

Listing 3-2.  Print Average, Testing for a Zero Count

 1 /// Read integers and print their average.
 2 /// Print nothing if the input is empty.
 3
 4 #include <iostream>
 5
 6 int main()
 7 {
 8    int sum{0};
 9    int count{};
10    int x;
11    while (std::cin >> x)
12    {
13        sum = sum + x;
14        count = count + 1;
15    }
16
17    if (count != 0)
18        std::cout << "average = " << sum / count << ' ';
29 }

Remember that != is the C++ syntax for the ≠ operator. Thus count != 0 is true when count is not zero, which means the program has read at least one number from its input.

Suppose you were to run the program with the following input:

2   5   3

What do you expect as the output?

_____________________________________________________________

Try it. What is the actual output?

_____________________________________________________________

Did you get what you expected? Some languages use different operators for integer division and floating-point division. C++ (like C) uses the same operator symbol and depends on the context to decide what kind of division to perform. If both operands are integers, the result is an integer.

What do you expect if the input is

2   5   4

_____________________________________________________________

Try it. What is the actual output?

_____________________________________________________________

Integer division truncates the result toward zero, so the C++ expression 5 / 3 equals 4 / 3 equals 1.

The other arithmetic operators are - for subtraction, * for multiplication, and % for remainder. C++ does not have an operator for exponentiation.

Listing 3-3 asks for integers from the user and tells the user whether the number is even or odd. (Don’t worry about how input works in detail; Exploration 5 will cover that.) Complete line 10.

Listing 3-3.  Testing for Even or Odd Integers

 1 /// Read integers and print a message that tells the user
 2 /// whether the number is even or odd.
 3
 4 #include <iostream>
 5
 6 int main()
 7 {
 8     int x;
 9     while (std::cin >> x)
10         if (                   )           // Fill in the condition.
11             std::cout << x << " is odd. ";
12         else
13             std::cout << x << " is even. ";
14 }

Test your program. Did you get it right?

_____________________________________________________________

I hope you used a line that looks something like this:

if (x % 2 != 0)

In other words, a number is odd if it has a non-zero remainder after dividing it by 2.

You know that != compares for inequality. How do you think you should write an equality comparison? Try reversing the order of the odd and even messages, as shown in Listing 3-4. Complete the condition on line 10.

Listing 3-4.  Testing for Even or Odd Integers

 1 /// Read integers and print a message that tells the user
 2 /// whether the number is even or odd.
 3
 4 #include <iostream>
 5
 6 int main()
 7 {
 8     int x;
 9     while (std::cin >> x)
10         if (                   )           // Fill in the condition.
11             std::cout << x << " is even. ";
12         else
13             std::cout << x << " is odd. ";
14 }

To test for equality, use two equal signs (==). In this case:

if (x % 2 == 0)

A common mistake that new C++ programmers make, especially those who are accustomed to SQL and similar languages, is to use a single equal sign for comparison. In this case, the compiler usually alerts you to the mistake. Go ahead and try it, to see what the compiler does. What message does the compiler issue when you use a single equal sign in line 10?

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

A single equal sign is the assignment operator. Thus, the C++ compiler thinks you are trying to assign the value 0 to the expression x % 2, which is nonsense, and the compiler rightly tells you so.

What if you want to test whether x is zero? Modify Listing 3-1 to print a message when count is zero. Once you get the program right, it should look something like Listing 3-5.

Listing 3-5.  Print Average, Testing for a Zero Count

 1 /// Read integers and print their average.
 2 /// Print nothing if the input is empty.
 3
 4 #include <iostream>
 5
 6 int main()
 7 {
 8     int sum{0};
 9     int count{};
10     int x;
11     while (std::cin >> x)
12     {
13         sum = sum + x;
14         count = count + 1;
15     }
16
17     if (count == 0)
18         std::cout << "No data. ";
19     else
20         std::cout << "average = " << sum / count << ' ';
21 }

Now modify Listing 3-5 to use a single equal sign on line 17. What message does your compiler issue?

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

_____________________________________________________________

Most modern compilers recognize this common error and issue a warning. Strictly speaking, the code is correct: the condition assigns zero to count. Recall that a condition of zero means false, so the program always prints No data., regardless of how much data it actually reads.

If your compiler does not issue a warning, read the compiler’s documentation. You might have to enable a switch to turn on extra warnings, such as “possible use of assignment instead of comparison” or “condition is always false.”

As you can see, working with integers is easy and unsurprising. Text, however, is a little trickier, as you will see in the next Exploration.

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

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