4: Numbers and Selection

What We Will Cover


Continuations

Homework Questions?

Questions from last class?

  • Who is thinking about pair programming?
  • Pair programming is worth extra credit
  • What is the value of the expression: 'd' - 'a' + 'A'?

Homework Discussion Questions (Thursday)

  1. How easy were turtle graphics to use?
  2. Did anyone notice a pattern in the angles for creating the objects?
  3. What is a term used for seeing an overall pattern in similar tasks?
  4. What other graphics capabilities would you like to see?

4.1: More About Numbers

Learner Outcomes

At the end of the lesson the student will be able to:

  • Describe exponential (scientific) notation
  • Format numbers during output
  • Discuss the reasons to use named constants instead of numbers
  • Rewrite assignment statements into shortcut alternatives
  • Generate code to convert data from one type to another
  • Diagnose problems with arithmetic precision and range and formulate solutions

4.1.1: Numbers and Arithmetic

  • Recall that C++ uses the following operators for arithmetic:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder)
  • The dash is also used for negation (minus sign)
  • We write arithmetic expressions using combinations of numbers, variables and operators
  • For example:
    double area = 0.0, radius = 4.4;
    area = 3.14159 * radius * radius;
    
  • Also recall that the results of integer division are truncated
    7 / 2       // 3
  • You must use modulus operator (%) to get the remainder value
    7 % 2       // 1 (remainder)
  • In addition, you use mathematical functions for more complex operations
    cout << sqrt(3.0 * 3) << endl;
  • C++ processes arithmetic expressions in the same order (precedence) as algebra:
    1. Parenthesis: ( )
    2. Function calls
    3. Unary operators: +, -
    4. Multiplication, division, modulus: *, /, %
    5. Addition, subtraction: +, -
  • Since parenthesis are processed first, you use parenthesis to change the order of operations
  • Now that we understand the basics of C++ arithmetic, we need to explore some additional features, limitations and quirks
  • We explore these items in the next exercise

4.1.2: Exponential Notation

  • Floating-point numbers can use exponential notation, which is similar to scientific notation
  • Exponential notations lets us express both very large and very small values in a compact form
  • For example:
Decimal Notation Scientific Notation Exponential Notation
1234 1.234 x 103 1.234e3
98765 9.8765 x 104 9.87654e4
0.0123 1.23 x 10-2 1.23e-2
0.000625 6.25 x 10-4 6.25e-4
  • The letter E stands for Exponent
  • The number following the E is the power of 10 to multiply the first number by
  • Thus, "E" means "times ten raised to the power"
  • An easy way to multiply by 10 is to move the decimal place for a number
  • A positive power of 10 moves the decimal point to the right
  • A negative power of 10 moves the decimal point to the left

How Large is 1.7E308?

  • The largest possible double is 17 followed by 307 zeros
  • How large is that?
  • The current estimate of the number of atoms in the universe is between 1.0e79 to 1.0e81
  • Mathematicians use the term "googol" for a very large number: 1.0e100
  • Data type double easily encompasses these numbers
  • What large number cannot be represented by type double?

4.1.3: Decimal Formatting

  • Sometimes programs may not display numbers as you would expect!
  • Consider the following program and what it will display:
    #include<iostream>
    using namespace std;
    
    int main() {
        double price = 78.50;
        cout << "The price is $" << price << endl;
    }
    
  • We must explicitly tell C++ how to output numbers in our programs!
  • "Magic Formula" to force decimal places:
    cout.setf(ios::fixed);     // fixed notation, not scientific
    cout.setf(ios::showpoint); // show decimal point
    cout.precision(2);         // show 2 decimal places
    
  • Once we set the decimal formatting, it stays set
  • When we set the state of an object like cout, it is sometimes referred to as "setting a flag"
  • In programming, a flag is used to store a particular code or setting
  • A flag is like the small flags used on mailboxes to indicate to the mail carrier that a letter is waiting to be collected

    Mailbox with flag

  • In other words, a flag is used to signal a condition
  • If we want to reset a formatting flag, we use cout.unsetf()
  • For instance:
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    
  • The setf() function has many other formatting flags as well
  • We will cover output formatting in more detail in a few weeks
  • If you are curious in the meantime see: Format flags

4.1.4: Constants and Magic Numbers

  • A constant variable (or constant) is a variable that cannot change after being assigned a value
  • Sounds oxymoronic, but is actually quite useful
  • To declare a constant, we use the keyword: const
    const int MY_CONST = 1;
  • Note that you must assign a value when the constant is declared
  • Also note that the name is all uppercase letters with an underscore separator
  • This is a common coding convention that you must follow

Magic Numbers

  • Imagine that you are a programmer hired to modify a payroll program
  • You come across the following section of code:
    double pay;
    pay = hours * 7.5 + (hours / 40)
          * (hours - 40) * 7.5 * 0.5;
    
  • The numbers are important to the program, but what do they mean?
  • Numbers like these are called "magic numbers"
  • They are magic because the value or presence is unexplainable without more knowledge
    • Often, no one knows what they mean after 3 months, including the author
  • A programmer can often infer the meaning of numbers after reading the code carefully
  • A much better coding style is to use named constants rather than literal numbers
  • For example:
    const double WAGE = 7.5;
    const double OVERTIME_ADDER = 0.5;
    const int HOURS_PER_WEEK = 40;
    double pay;
    pay = hours * WAGE + (hours / HOURS_PER_WEEK)
          * (hours - HOURS_PER_WEEK) * WAGE * OVERTIME_ADDER;
    
  • Now it is much easier to understand the code and see any problems or limitations in it
  • Another reason to use named constants is that it is easier to change the value of the number
  • In the above example, we can easily change the WAGE without making errors in other parts of our code

Programming Style: Constant Variables and Magic Numbers

  • Since the meaning of literal ("magic") numbers is hard to remember, you should declare constants instead:
    const int FEET_PER_YARD = 3;
    const double PI = 3.14159265358979323846;
    const double WAGE = 7.5;
    const double OVERTIME_ADDER = 0.5;
    const int HOURS_PER_WEEK = 40;
    
  • Note that the name is all uppercase letters with an underscore word-separator
  • This is a common coding convention that you must follow for your constants

More Information

Exercise 4.1

In this exercise we explore some additional numeric features of C++.

Specifications

  1. Copy the following program into a text editor and save it as price.cpp:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    #include <iostream>
    using namespace std;
    
    int main() {
        string name;
        double price = 0;
    
        cout << "Enter the product name: ";
        getline(cin, name);
        cout << "Price of the " << name << ": ";
        cin >> price;
    
        // Insert new statements here
    
        cout << "Total price: $" << price << endl;
    
        return 0;
    }
    
  2. Compile and run the starter program to make sure you entered it correctly.

    When you run the program, the output should look like this:

    Enter the product name: iPod Nano
    Price of the iPod Nano: 89.50
    Total price: $89.5
    

    Note the format of the numbers output for the total price. We will address this formatting issue later in the exercise.

  3. Run the program again for a product with a very high cost, like a Boeing 777:
    Enter the product name: Boeing 777
    Price of the Boeing 777: 212345678
    Total price: $2.12346e+08
    

    Note the format of the numbers output for the total price. This format is called exponential notation. For more information on exponential notation, see section: 4.1.2: Exponential Notation.

  4. Let us correct the formatting of the total price. Enter the following code before the statement that prints the total price:
    cout.setf(ios::fixed);     // fixed notation, not scientific
    cout.setf(ios::showpoint); // show decimal point
    cout.precision(2);         // show 2 decimal places
    

    These statements are referred to as the "magic formula" because they for C++ to output statements in a "standard" format. Note what each statement accomplishes. For more information, see section: 4.1.3: Decimal Formatting.

  5. Compile and run your program again and verify the output looks like:
    Enter the product name: Boeing 777
    Price of the Boeing 777: 212345678
    Total price: $212345678.00
    
  6. Let us add a constant that we will use later in our program. Enter the following code after the magic formula and before the statement that prints the total price:
    const int PERCENT = 100;
    

    A constant variable (or constant) is a variable that cannot change after being assigned a value. Using a constant lets us avoid using a vague number. For more information, see section: 4.1.4: Constants and Magic Numbers.

  7. Now we will add sales tax to the price of the product. Enter the following code after the constant and before the statement that prints the total price:
    double taxRate = 0;
    cout << "Enter sales tax rate (%): ";
    cin >> taxRate;
    double tax = price * taxRate / PERCENT;
    price += tax;
    

    Notice the last statement: price += tax;. This is an alternate way to code the statement: price = price + tax;. For more information, see section: 4.1.5: Assignment Operators.

  8. Compile and run your modified program and verify the output looks like:
    Enter the product name: iPod Nano
    Price of the iPod Nano: 89.50
    Enter sales tax rate (%): 8.5
    Total price: $97.11
    
  9. Now we will find the whole dollars and cents of the amount to demonstrate casting. Enter the following code after the statement that prints the total price and before the return statement:
    int dollars = (int) price;
    cout << "In whole dollars: $" << dollars << endl;
    

    Notice the (int) in the first statement. This is known as a type cast or just cast. For more information, see section: 4.1.6: Type Casting.

  10. Compile and run your modified program and verify the output looks like:
    Enter the product name: iPod Nano
    Price of the iPod Nano: 89.50
    Enter sales tax rate (%): 8.5
    Total price: $97.11
    In whole dollars: $97
    
  11. Submit your program source code to Blackboard as part of assignment 4.
  12. Also, work through the examples in section: 4.1.7: Arithmetic Precision and Range.

Completed Program

Once you are finished, your source code should look like the following (excluding comments):

Listing of price.cpp

Check Yourself

As time permits, be prepared to answer these questions. You can find additional information in the sections that follow.

  1. How are very large or very small numbers floating point numbers formatted by default when displayed with cout? (4.1.2)
  2. What is the "magic formula" for displaying numbers in decimal notation? (4.1.3)
  3. What is the purpose of each line of the magic formula? (4.1.3)
  4. What is the code to declare a constant double named BIG_NUM and assign it a value of 100,000? (4.1.4)
  5. What is an equivalent statement for each of the following shortcut assignments? (4.1.5)
    1. a += b;
    2. a -= b;
    3. a *= b;
    4. a /= b;
    5. a %= b;
  6. How many ways can you add the integer 1 to a variable named index? List each way. (4.1.5)
  7. Which is a valid typecast? (4.1.6)
    1. a(int)
    2. int:a;
    3. (int)a;
    4. to(int, a);
  8. How can you truncate the decimal part of double variable? (4.1.6)
  9. What happens when you increase the value of a signed integer beyond its range? (4.1.7)
  10. How many digits that can be accurately stored in a type float? double? (4.1.7)
  11. What is the output of the following code fragment? Why? (4.1.7)
    cout.precision(17);
    double r = sqrt(2);
    if (r * r == 2) {
        cout << "sqrt(2) squared is 2\n";
    } else {
        cout << "sqrt(2) squared is not 2 but "
             << (r * r) << endl;
    }
    

4.1.5: Assignment Operators

  • As we discussed before, we assign values to variables using an equal (=) sign
    int sum = 0;
  • However, the equal sign is really an assignment operator and does not denote equality
  • Thus, unlike math, you can have the same variable on both sides of an equals sign:
    int sum = 25;    // initialize sum to 25
    sum = sum + 10;  // add to sum
    
  • Note that the value of the variable is changed in the second line
  • Reading variables from memory does not change them
  • Values placed into a variable replace (overwrite) previous values:

    Assigning a value to a variable

Shortcut Assignment Operators

  • We can use additional operators to calculate values and assign them to the variable on the left all in one statement
    • Known as shortcut assignment operators
  • The general syntax is:
    variable op= expression;
  • Where op is one of the five arithmetic operators: +, -, *, /, %
  • For example, the following two statements create the same result:
    x = x + 3;
    x += 3;
    
  • Shown below are the assignment operators with examples of how they are used

Summary of Assignment Operators

Operator Description Example Equivalent To
= Assigns the value of the expression on the right to the variable on the left x = 3  
+= Adds the expression on the right to the variable on the left x += 3 x = x + 3
-= Subtracts the expression on the right from the variable on the left x -= 3 x = x - 3
*= Multiplies the expression on the right to the variable on the left and saves the result in the variable on the left x *= 3 x = x * 3
/= Divides the variable on the left by the expression on the right and saves the result in the variable on the left x /= 3 x = x / 3
%= Calculates the remainder from dividing variable on the left by the expression on the right and saves the result in the variable on the left x %= 3 x = x % 3

Increment and Decrement Operators

  • Another arithmetic shortcut is the increment and decrement operators
  • The increment operator (++) adds 1 to a variable's value
  • Preincrement adds 1 before returning the value of a variable
    ++sum;
  • Post-increment returns the current value of variable then adds 1
    sum++;
  • The decrement operator works like the increments operator, except it subtracts 1 from the variable
  • For instance:
    --sum
    sum--
    
  • Pre- and post- increment matters when the operation is part of a larger expression
  • For example, consider the code:
    int x = 5;
    int y = x++;
    cout << "x=" << x << " y=" << y;
    
  • You may expect y to be 6 after this code executes
  • Instead, y has the value of 5
  • The reason is that ++ after a variable (post-increment) is equivalent to:
    y = x;
    x = x + 1;
    
  • On the other hand, ++ before a variable (pre-increment) is equivalent to:
    x = x + 1;
    y = x;
    

4.1.6: Type Casting

Cast: change the data type of the returned value of an expression

  • Recall that different data types are stored in different forms
  • Sometimes you need to change from one form to another
  • For example: arithmetic adding a double and an int value
  • C++ will automatically cast one value to another
    • Known as implicit casting or type coercion
  • Programmers can also explicitly cast data types
  • Explicit casting changes the data type for a single use of the variable
  • Precede the variable name with the new data type in parentheses:
    (dataType) variableName
    
  • The type is changed only for the single use of the value
  • For example:
    double x = 2.99999;
    x = (int) x;
    cout << x << endl;
    
  • The value of x is converted from type double to int before assigning the converted value to x
  • However, x remains a type double and the cast only applies to a single use of x
  • The above example shows a common use of casting -- removing the decimal part of a floating-point number
  • Note that the decimal portion of the number is truncated and NOT rounded
  • Decimal part is lost (discarded, ignored, thrown away)
  • Another use is to convert an int to a double when dividing two int numbers and a decimal result is desired
  • For example:
    double x = (double) 9 / 5;
    cout << x << endl;
    
  • Still another use is to prevent compiler warnings
  • For example:
    double x = 2.3;
    int n = x;
    cout << n << endl;
    
  • The above may cause a compiler warning with the settings we use:
    warning: converting to `int' from `double'
  • To remove the warning, we use a cast:
    double x = 2.3;
    int n = (int) x;
    cout << n << endl;
    
  • This tells the compiler that you intended to convert from double to int

New Style Casting

  • C++ has many styles of casting
  • Newer style of casting is of the form:
    static_cast<toType>(expression)
  • For example:
    int x = 9;
    int y = 2;
    double ans = x / static_cast<double>(y)
    

Example Application Using Casting: cast.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main() {
    double input;
    cout << "Enter hours: ";
    cin >> input;

    int hours = (int) input; // prevents warning
    int minutes = (int) ((input - (int) input) * 60);
    cout << "In hours and minutes, this is "
         << hours << ":" << minutes << endl;
    return 0;
}

4.1.7: Arithmetic Precision and Range

  • There are only a finite set of numbers in numerical data types
  • This can lead to problems for the unwary

Integer Overflow

  • What happens when an integer is too big for its type?
    cout << "Big number: ";
    cout << 2147483647 + 1 << endl;
    cout << "Small number: ";
    cout << -2147483647 - 2 << endl;
    
  • The number "wraps around" from the highest number to the lowest
  • You must be careful that your program will not go beyond the range of its data types

More Integer Types

  • To increase the range, C++ has the long data type
  • Originally, the long data type was 32 bits while the int was 16 bits
  • However, with the development of 32 bit computers, the int value was extended to 32 bits but the long was left at 32 bits
  • Thus, at the present time, int and long are the same size on most computers
  • In addition, C++ has unsigned integer types you can use to change the range
  • Rather than integer ranges from -2147483647 to 2147483647, unsigned int ranges from 0 to 4294967295

Floating-Point Precision and Range

  • Floating-point numbers are not exact representations of real numbers
  • Rounding errors occur in repeated calculations
  • Type double has about twice the precision of type float
  • However, even type double can have rounding errors
    cout.precision(17);
    cout << .8F + .1F << endl;
    cout << .8 + .1 << endl;
    
  • When floating point numbers get too large, they are set to inf
  • For instance:
    cout << 2E38F + 2E38F << endl;
  • Similarly, when numbers are too small they are set to 0.0

The Moral

  • Integer and floating-point data types work well most of the time
  • However, if you work with large positive or negative integers, you must be sure you do not exceed the range of the data type
  • Also, floating-point numbers have limited precision
  • When math operations are performed repeatedly, they can become less precise
  • Thus you must be careful of precision when using floating-point numbers

4.1.8: Summary

  • In this section we discussed more details about programming with numbers
  • When floating-point numbers get very large or very small, C++ displays them using exponential (scientific) notation
  • cout includes special functions to specify the output of type double
  • The following magic formula lets us display numbers with 2 decimal places:
    cout.setf(ios::fixed);     // fixed notation, not scientific
    cout.setf(ios::showpoint); // show decimal point
    cout.precision(2);         // show 2 decimal places
    
  • Constants are a variable that cannot change after it is first assigned a value
  • Constants are often used to apply meaningful names to numbers
  • Another reason to use named constants is that it is easier to change the value of the number
  • C++ has assignment variations of the form:
    variable <op>= expression;
  • C++ will automatically cast data of one type to another when necessary
  • However, you can explicitly cast values to a different type.
  • You must explicitly cast when C++ does not perform as you want.
  • Not all numbers can be represented accurately by primitive C++ types
  • Integer values have a limited range
  • If your program assigns values too high or too low, integers wrap around
  • Floating-point numbers usually have enough range
  • However, they often suffer from lack of precision
    cout.precision(17);
    cout << .8F + .1F << endl;
    cout << .8 + .1 << endl;
    
  • Type double has about twice the precision of type float
  • When floating point numbers get too large, they are set to inf
  • Similarly, when too small they are set to 0.0

4.2: More Turtle Capabilities

Learner Outcomes

At the end of the lesson the student will be able to:

  • Clear the turtle graphics window
  • Display text messages and numbers in the graphics window
  • Process user input in turtle graphic programs
  • Pause the display of shapes in turtle graphics programs

4.2.1: More Amazing Turtle Tricks

  • So far we have discussed how to create shapes using turtle graphics
  • But a Turtle has more capabilities that we can use
  • In this section we will look at how to read keystrokes and print text and numbers in a Turtle window
  • Also, we will look at how to clear the tracks of a turtle drawing
  • But first, we will teach our turtle a new trick: sleeping

Sleeping

  • A favorite activity of a turtle is sleeping
  • We can have our turtle take a short nap by using the command:
    turtleName.sleep(timeInMilliseconds);
    
  • Where:
    • turtleName: the name of your Turtle object
    • timeInMilliseconds: how long to sleep in milliseconds
  • For example:
    Turtle myrtle;
    myrtle.sleep(1000);
    
  • In the above example, myrtle sleeps for one second, which is 1000 milliseconds
  • Commands like sleep() are often used to slow a computer's processing or output for animation
  • Note that this command does not work well on the Mac (so do not use it)

4.2.2: Clearing Tracks

  • One clever trick of a turtle is to clear its tracks
  • To erase the tracks your turtle makes, you can use the command:
    turtleName.clear();
    
  • Where:
    • turtleName: the name of your Turtle object
  • In the following example, myrtle draws a square, sleeps for one second, and then erases the square

Example Program Using clear()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "turtlelib.cpp"

int ccc_win_main() {
    Turtle myrtle;
    myrtle.right(90);

    myrtle.forward(5);
    myrtle.left(90);
    myrtle.forward(5);
    myrtle.left(90);
    myrtle.forward(5);
    myrtle.left(90);
    myrtle.forward(5);
    myrtle.left(90);

    myrtle.sleep(1000);
    myrtle.clear();

    return 0;
}

4.2.3: Turtle Graphics Input and Output

  • You may have noticed that cin and cout do not work with turtle graphics
  • That is because cin and cout are used for console input and output
  • When you work with different programming environments, like graphics or files, you must use different input and output techniques
  • We will learn different input and output techniques this term for our different environments

Printing Text and Numbers

  • So far we have displayed lines as output for turtle graphics
  • However, a Turtle can display text and numbers as well
  • To display text or numbers, you can use the command:
    turtleName.print(textOrNumber);
    
  • Where:
    • turtleName: the name of your Turtle object
    • textOrNumber: the text string or number to display
  • For example:
    myrtle.moveTo(-5, 5);
    myrtle.print("My name is Myrtle");
    
  • Your turtle will display the text or number at its current location
  • Thus you need to move your turtle to the desired coordinates before using print()

Keyboard Input

  • A turtle knows three commands for getting keyboard input from a user:
    • turtleName.getString(): reads a string from the keyboard
    • turtleName.getInt(): reads an integer number from the keyboard
    • turtleName.getDouble(): reads a floating point (double) number from the keyboard
  • Recall that prompting is a good idea when asking for user input, so that the user knows what to type
  • Thus, each of the commands includes a prompt string that is displayed while waiting for the user to enter data from the keyboard
  • For example:
    string msg = myrtle.getString("Enter a message: ");
    myrtle.moveTo(-5, 5);
    myrtle.print(msg);
    
  • We will explore how to use turtle IO in the next exercise

Exercise 4.2

In this exercise we look at how to use the new capabilities of the Turtle class.

Specifications

  1. Copy the following program into a text editor, save it as turtleio.cpp, and then compile and run the starter program to make sure you copied it correctly.
    #include "turtlelib.cpp"
    
    int ccc_win_main() {
        // Enter code here
    
        return 0;
    }
    

    When you run the program, you should see a graphics window appear. If you encounter any syntax errors, or do not see the window, correct your errors or get help from a classmate or the instructor before continuing.

  2. Add the following code to construct a turtle:
    Turtle tattle;

    For more information on constructing objects see lesson 3.3.4: Constructing Objects Without Parameters

  3. Let us use the object we created to read an integer number from the keyboard. Add the following command after the object you constructed in the previous step:
    int num1 = tattle.getInt("Enter an integer: ");
    

    For more information see section 4.2.3: Turtle Graphics Input and Output

  4. Compile and execute the code and verify you can enter a number into the graphics window.

    If you encounter any syntax errors, cannot see the prompt, or cannot enter a number, then correct your errors or get help from a classmate or the instructor.

  5. Now let use display the number we entered. Add the following command after the input command of the previous step:
    tattle.moveTo(-8, 8);
    tattle.print(num1);
    

    For more information see section 4.2.3: Turtle Graphics Input and Output

  6. Compile and execute the code and verify the number you enter is displayed in the graphics window.

    If you encounter any syntax errors or cannot see the number, then either correct your errors or get help from a classmate or the instructor.

  7. Now add code like the following to enter both a double and a string, and then display the values the user enters:
    double num2 = tattle.getDouble("Enter a double: ");
    tattle.moveTo(-8, 7);
    tattle.print(num2);
    
    string msg = tattle.getString("Enter a message: ");
    tattle.moveTo(-8, 6);
    tattle.print(msg);
    

    For more information see section 4.2.3: Turtle Graphics Input and Output

  8. Now let us add some simple animation to our turtle by pausing and then drawing a square around the display of numbers and text. Add code like the following after the code to enter and display numbers and strings:
    tattle.sleep(1000);
    tattle.moveTo(-9, 5);
    tattle.right(90);
    tattle.forward(5);
    tattle.left(90);
    tattle.forward(4);
    tattle.left(90);
    tattle.forward(5);
    tattle.left(90);
    tattle.forward(4);
    tattle.left(90);
    

    For more information on sleep() see section 4.2.1: More Amazing Turtle Tricks

  9. Compile and run your program to verify the final output looks like the following:

    Output of turtleio.cpp

    If your code does not work correctly, compare it to the listing shown below.

  10. Submit your "turtleio.cpp" source code to Blackboard as part of assignment 4.

Listing of turtleio.cpp

Listing of turtleio.cpp

Check Yourself

As time permits, be prepared to answer these questions. You can find additional information in the sections that follow.

  1. What happens when you run the sleep command? (4.2.1)
  2. What command do you use to clear the turtle graphics window? (4.2.2)
  3. What command do you use to text or numbers in a turtle graphics window? (4.2.3)
  4. What command do you use to read an integer from the keyboard? a double number? A string? (4.2.3)
  5. What is the purpose of the string, "Enter an integer",in the following code? (4.2.3)
    int num1 = tattle.getInt("Enter an integer: ");
    
  6. In the above code, why do we need to assign the command to the variable num1? (4.2.3)

4.2.4: Summary

  • In this section we looked at some other capabilities of a Turtle object
  • One of those capabilities was to pause, or sleep, for a brief time
  • For example:
    Turtle myrtle;
    myrtle.sleep(1000);
    
  • Another capability was to erase all the tracks of the Turtle object using the clear() command
  • For example:
    myrtle.clear();
    
  • To display values in the turtle graphics window, you cannot use cout
  • Instead, you can use the print() command like:
    myrtle.print("My name is Myrtle");
    
  • To read user input from the keyboard, you cannot use cin
  • Instead, you can use one of the following "get" commands:
    • getString(): reads a string from the keyboard
    • getInt(): reads an integer number from the keyboard
    • getDouble(): reads a floating point (double) number from the keyboard
  • Since it is a good idea to prompt the user when asking for input, each of the commands includes a prompt string
  • For example:
    string msg = myrtle.getString("Enter a message: ");
    
  • The prompt is displayed while waiting for the user to type the input on the keyboard
  • Note that you must assign the "get" command to a variable to save the information entered at the keyboard

4.3: Making Selections

Learner Outcomes

At the end of the lesson the student will be able to:

  • Discuss what is meant by the term flow of control
  • Make use of relational expressions to make decisions
  • Implement decisions using if statements
  • Compare numbers, characters and strings
  • Develop strategies for processing input and handling errors

4.3.1: Flow of Control

  • The programs we have worked with so far simply execute a list of instructions
  • We arrange our command statements in a particular order to get the result we want
  • When the program reaches the end of the list of instruction, it stops
  • Except for differences in the input, these programs always work the same way
  • To create more interesting and useful programs, we need our programs to make decisions and carry out different actions
  • For example, if the user enters an incorrect value, we want our program to warn the user with an error message
  • However, if the user enters a correct value, we do not want to display an error message
  • For our programs to make decisions and carry out different actions, we use statements to change the flow of control
  • Flow of control (or control flow) refers to the order in which programs execute instructions
  • We will look at two major ways to change the flow of control:
    • Conditional (selection) statements
    • Loops (repetition) statements
  • In this section, we will look at how to use the conditional statements:
    if
    if...else
    
  • Later will look at more selection statements and how to use the loop statements

4.3.2: The Value of a Relationship

  • To make a selection (or repetition statement) we need to code a test condition
  • The computer uses the test to decide whether or not to execute the statement
  • One way to code a test condition is to use a relational expression

Relational Expressions

  • In addition to arithmetical operations, all computers can compare numbers
  • Many decisions can be reduced to choosing between two numbers
  • For instance, did the user enter a number equal to the correct guess
  • Expressions that compare numbers are called relational expressions
  • Simple relational expressions have one relational operator comparing two operands:

    relational expression

  • You can see the relational operators of C++ in the following table

Relational Operators

Math Name C++ Examples   Result Notes
= Equal to == 5 == 10
2 == 2
false
true
Do not confuse with = which is assignment.
Not equal to != 5 != 10
2 != 2
true
false
The ! is like the line that "crosses through" the equal sign.
< Less than < 5 < 10
5 < 5
5 < 2
true
false
false
Less than or equal to <= 5 <= 10
5 <= 5
5 <= 2
true
true
false
Be careful not to write =<. Code the symbols in the order people normally say them.
> Greater than > 5 > 10
5 > 5
5 > 2
false
false
true
Greater than or equal to >= 5 >= 10
5 >= 5
5 >= 2
false
true
true
Be careful not to write =>. Code the symbols in the order people normally say them.

Check Yourself

Formulate the following conditions in C++:

4.3.3: Comparing Characters and Strings

  • Character data can be evaluated using relational operators as well
  • Comparing characters works because C++ stores characters as numbers using ASCII codes
  • Note that letters nearer to the start of the alphabet have lower numerical values
  • Thus a numerical comparison can decide the alphabetical order of characters

Example Program Comparing Characters

1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
using namespace std;

int main() {
    cout << boolalpha; // output true or false
    cout << "'A' < 'B': " << ('A' < 'B') << endl;
    cout << "'A' > 'B': " << ('A' > 'B') << endl;
    cout << "'A' <= 'Z': " << ('A' <= 'Z') << endl;
    cout << "'X' >= 'Y': " << ('X' >= 'Y') << endl;
    cout << "'X' == 'X': " << ('X' == 'X') << endl;
    cout << "'X' != 'X': " << ('X' != 'X') << endl;
}

Comparing Strings

  • We can compare strings using relational operators as well
  • C++ compares two strings using lexicographical order (a.k.a. alphabetic order)
  • For example, "car" is less than "cat":
    c a r
    c a t
  • Also, "car" is less than "card"
    c a r
    c a r d

Example Program Comparing Strings

1
2
3
4
5
6
7
8
9
10
11
#include<iostream>
using namespace std;

int main() {
    string s1, s2;
    cout << "Enter two strings: ";
    cin >> s1 >> s2;
    cout << boolalpha; // output true or false
    cout << "s1 <= s2: " << (s1 <= s2) << endl;
    cout << "s1 > s2: " << (s1 > s2) << endl;
}

More Information

4.3.4: Using if Statements

  • The simplest control-flow statement is an if statement
  • We use an if statement to select whether or not to execute a set of statements
  • An if statement has two parts: a test and a body
  • The body consists of zero or more statements
  • The statements in the body execute if and only if the test evaluates to true
  • If the test condition evaluates to false, the computer skips the code
  • Syntax:
    if (test) {
       statement1
       statement2
       ...
    }
    
  • Where:
    • test: the test condition to evaluate
    • statementX: the statements to execute depending on the test
  • For example:
    if (7 == guess) {
        cout << "*** Correct! ***" << endl;
    }
    
  • For clarity:
    • Write the if on a different line than the executed block
    • Indent statements 3-4 spaces within the curly braces
  • You can see an example of an if statement in the following example

Example Program With an if Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;


int main() {
    const int ANSWER = 7;

    int guess = 0;
    cout << "I'm thinking of a number between"
         << " 1 and 10.\nCan you guess it?\n\n"
         << "Enter your guess: ";
    cin >> guess;

    if (ANSWER == guess) {
        cout << "*** Correct! ***" << endl;
    }
    return 0;
}

About those Curly Braces

  • Technically, the if statement affects only the single statement that follows
  • We use curly braces to make that one statement into a block of statements
  • This allows us to put any number of statements within the body
  • Curly braces are not always required, but the best practice is to always include them

4.3.5: Using if-else Statements

  • Sometimes we want to choose between two actions
  • If a condition is true
    • then do this
  • Otherwise it is false
    • so do something else
  • To make this type of selection we use an if...else statement
  • Syntax:
    if (test) {
       statements1
    } else {
       statements2
    }
    
  • Where:
    • test: the test condition to evaluate
    • statementsX: the statements to execute depending on the test
  • For example:
    if (7 == guess) {
        cout << "*** Correct! ***\n";
    } else {
        cout << "Sorry, that is not correct.\n";
        cout << "Try again.\n";
    }
    
  • Note that there is no test condition for the else clause
  • The decision on which set of statements to use depends on only one condition
  • Note that you could write an if-else as a pair of complementary if statements instead, like:
    if (7 == guess) {
        cout << "*** Correct! ***\n";
    }
    if (7 != guess) {
        cout << "Sorry, that is not correct.\n";
        cout << "Try again.\n";
    }
    
  • However, it is easier and clearer to write an if-else statement instead
  • For clarity, write the if and else parts on different lines than the other statements
  • Also, indent the other statements
  • You can see an example of an if-else statement in the following example

Example Program With an if-else Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;


int main() {
    const int ANSWER = 7;

    int guess = 0;
    cout << "I'm thinking of a number between"
         << " 1 and 10.\nCan you guess it?\n\n"
         << "Enter your guess: ";
    cin >> guess;

    if (ANSWER == guess) {
        cout << "*** Correct! ***\n";
    } else {
        cout << "Sorry, that is not correct.\n";
        cout << "Try again.\n";
    }
    return 0;
}

Formatting the if Statement

  • It is important to format the if statement correctly
    if (7 == guess) {
        cout << "*** Correct! ***\n";
    } else {
        cout << "Sorry, that is not correct.\n";
        cout << "Try again.\n";
    }
    
  • Note how the conditional code is indented inside both the if and else portions
  • This lets us easily see which code is conditional and which is not
  • Also note the placement of curly braces
  • Different groups have different practices for placing curly braces for placing curly braces of if and if-else statements
  • In practice, you should use the style dictated by your group's policy
    • Or your professor's instructions
  • For the acceptable styles for this course see my instructions on: Curly Braces

Exercise 4.3

In this exercise we explore the use of relational operators with if statements to create a simple game.

Specifications

  1. Copy the following program into a text editor, save it as selection.cpp, and then compile and run the starter program to make sure you copied it correctly.
    #include <iostream>
    using namespace std;
    
    int main() {
        int guess = 0;
        cout << "I'm thinking of a number between"
             << " 1 and 10.\nCan you guess it?\n\n"
             << "Enter your guess: ";
        cin >> guess;
        cout << "You entered: " << guess << endl;
    
        // Insert new statements here
    
        return 0;
    }
    
  2. Now we want to set the value for a correct guess. Enter the following code:
    const int ANSWER = 7;
    

    A constant is a good way to set the value. Because it is constant, we cannot accidentally change the value elsewhere in the program. Also, if we want to change the value of the correct guess, we only need to change it in one location in our program. For more information on constants, see section: 4.1.4: Constants and Magic Numbers.

  3. We want to let the user know if they entered a correct value. For this we need to add an if statement such as:
    if (ANSWER == guess) {
        cout << "*** Correct! ***" << endl;
    }
    

    Statements inside the curly braces only execute if the test condition in the parenthesis, (ANSWER == guess), evaluates to true. For more information, see section: 4.3.4: Using if Statements.

  4. Compile and run your program again and verify the output looks like:
    I'm thinking of a number between 1 and 10.
    Can you guess it?
    
    Enter your guess: 7
    You entered: 7
    *** Correct! ***
    

    If you rerun the program and enter a number different than the value of ANSWER (like 9) then the message saying correct will NOT appear.

  5. For a friendlier game output, we should give a message when the user enters an incorrect value. For this we need to replace our if statement with an if-else statement like:
    if (ANSWER == guess) {
        cout << "*** Correct! ***\n";
    } else {
        cout << "Sorry, that is not correct.\n";
        cout << "Please try again.\n";
    }
    

    Statements inside the curly braces of the else clause only execute if the test condition in the parenthesis, (ANSWER == guess), evaluates to false. For more information, see section: 4.3.5: Using if-else Statements.

  6. Compile and run your program again and verify the output looks like:
    I'm thinking of a number between 1 and 10.
    Can you guess it?
    
    Enter your guess: 9
    You entered: 9
    Sorry, that is not correct.
    Rerun and try again.
    

    The error message should appear for any number other than the correct guess.

  7. One problem with our program is that a user may enter numbers outside the range of 1 through 10. We can test for this condition with one or more if statements. Add this code to your program after the input statement and before the other if statements:
    if (guess < 1) {
        cout << "Error: guess must be >= 1\n";
        return 1;
    }
    

    Checking user input is a common use of if statements. This type of code is known as input validation or input verification. For more information, see section: 4.3.6: Input Validation.

  8. Compile and run your program again and verify the output looks like:
    I'm thinking of a number between 1 and 10.
    Can you guess it?
    
    Enter your guess: 0
    You entered: 0
    Error: guess must be >= 1
    

    The error message should appear for any number other than the correct guess.

  9. You can nest if statements inside either the if or else clause. We can use this when we have a series of tests to make. Replace all the if and if-else statements with the following code:
    if (guess < 1) {
        cout << "Error: guess must be >= 1\n";
    } else if (guess > 10) {
        cout << "Error: guess must be <= 10\n";
    } else if (guess != ANSWER) {
        cout << "Sorry, that is not correct.\n";
    } else {
        cout << "*** Correct! ***\n";
    }
    

    Conditions are checked in order until the one of the conditions evaluates to true. Once one condition evaluates to true, the rest of the tests are skipped. If no test condition evaluates to true then the else clause executes as the default case. For more information, see section: 4.3.6: Nested if Statements.

  10. Compile your program and run it several times to see what message you get when you enter each of the following as a guess:
    1. 0
    2. 7
    3. 9
  11. Submit your program source code to Blackboard as part of assignment 4.

Check Yourself

As time permits, be prepared to answer these questions. You can find more information by following the links after the question.

  1. What is meant by the term "flow of control"? (4.3.1)
  2. What is the default flow-of-control operation after a statement finishes executing? (4.3.1)
  3. What is a relational expression and why are they used? (4.3.2)
  4. Of the following pairs of strings, which comes first in lexicographic order? (4.3.3)
    1. "Harry", "Potter"
    2. "Harry", "Hairy"
    3. "car", "C++"
    4. "car", "Car"
    5. "car model", "carburetor"
  5. What part of an if statement is indented? (4.3.4)
  6. What is the value of x after the following code segment? (4.3.4)
    int x = 5;
    if (x > 3) {
        x = x - 2;
    } else {
        x = x + 2;
    }
    
  7. What is wrong with each of the following if statements after executing the code: (4.3.4)
    int guess;
    cout << "Enter your guess: ";
    cin >> guess;
    
    1. if (7 == guess) then cout << "You guessed 7!\n";
    2. if (guess = 7) cout << "You guessed 7!\n";
    3. if ("7" == guess) cout << "You guessed 7!\n";
  8. Does the syntax for an else clause include a test condition? (4.3.5)
  9. What is the output of the following code fragment? Why?
    cout.precision(17);
    double r = sqrt(2);
    if (r * r == 2) {
        cout << "sqrt(2) squared is 2\n";
    } else {
        cout << "sqrt(2) squared is not 2 but "
             << (r * r) << endl;
    }
    
  10. For the above example code fragment, what is a better test condition than (r * r == 2)?
  11. True or false? You can nest if statements in either the if clause, the else clause, or both. (4.3.6)
  12. If you have a series of test conditions, and only one can be correct, what is the sequence of if and else statement you should follow? (4.3.6)

4.3.6: Nested if Statements

  • Note that you can include if statements within other if statements
  • The inner if statement is evaluated only if the test condition of the outer if test first evaluates to true
  • The following code shows an example of a nested if statement

Example Showing a Nested if Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int main() {
    const int ANSWER = 7;

    int guess = 0;
    cout << "I'm thinking of a number between"
         << " 1 and 10.\nCan you guess it?\n\n"
         << "Enter your guess: ";
    cin >> guess;

    if (guess != ANSWER) {
        if (guess < ANSWER) {
            cout << "Your guess is too low.\n";
        } else {
            cout << "Your guess is too high.\n";
        }
    } else {
        cout << "*** Correct! ***\n";
    }

    return 0;
}

Nesting in the else Clause

  • You can also nest if statements in the else clause
  • The following code shows an example of a nested else if statement
  • Note the alignment of the nested statements
  • Instead of:
    if (guess < ANSWER) {
        cout << "Your guess is too low.\n";
    } else
        if (guess > ANSWER) {
            cout << "Your guess is too high.\n";
        } else {
            cout << "*** Correct! ***\n";
        }
    }
    
  • We use:
    if (guess < ANSWER) {
        cout << "Your guess is too low.\n";
    } else if (guess > ANSWER) {
        cout << "Your guess is too high.\n";
    } else {
        cout << "*** Correct! ***\n";
    }
    
  • This shows more clearly that we are making a single choice among multiple alternatives
  • Also, it prevents indentations from cascading to the right

Example Showing a Nested else if Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

int main() {
    const int ANSWER = 7;

    int guess = 0;
    cout << "I'm thinking of a number between"
         << " 1 and 10.\nCan you guess it?\n\n"
         << "Enter your guess: ";
    cin >> guess;

    if (guess < ANSWER) {
        cout << "Your guess is too low.\n";
    } else if (guess > ANSWER) {
        cout << "Your guess is too high.\n";
    } else {
        cout << "*** Correct! ***\n";
    }

    return 0;
}

4.3.7: Summary

  • All selection and repetition statements have a test condition
  • This test condition controls the operation of the statement
  • Relational operators are a common way to create a test condition
  • In this section we looked at how to implement decisions using an if statement
  • An if statement has two parts: a test and a body
  • For example:
    if (7 == guess) {
        cout << "*** Correct! ***" << endl;
    }
    
  • The if statement executes a block of code only if the test evaluates to true
  • It does nothing if the conditional expression evaluates to false
  • We can execute statements when the condition is false by using an else clause
  • For example:
    if (7 == guess) {
        cout << "*** Correct! ***\n";
    } else {
        cout << "Sorry, that is not correct.\n";
    }
    
  • We often implement test conditions using relational operators to create a relational expression
  • Relational operators include:
    ==  !=  <   <=  >   >=
  • We can use these relational operators with numbers, characters and strings
  • One common use of if statements is validation of user input
  • We can test the type of the input by using:
    if (cin.fail())
  • We looked at alternate strategies for testing the input type as well
  • In addition to checking the type, good programs validate the input values
  • For instance, if we want the user to enter a number greater than or equal to 1:
    if (guess < 1) {
        cout << "Error: guess must be >= 1\n";
        return 1;
    }
    
  • Also we noted that you can nest if statements within another if or else

4.4: Repetition (Loops)

Objectives

At the end of the lesson the student will be able to:

  • Use while statements to repeat sections of code
  • Discuss the usual parts of a loop
  • Describe what is meant by a main loop

4.4.1: Simple Loops

  • Sometimes we want to repeat a section of code
  • For instance, we may want to let a user run our program multiple times
  • When we want to repeat a section of code, we use a loop statement
  • A loop is a block of code that can execute repeatedly
  • Whether or not a program repeats a block of code is determined by a test condition
  • The test condition is checked each time through the loop
  • To set up the test condition, we write initialization code
  • In general, loops have three parts to them
    • Initialization code
    • Test condition -- evaluated during the loop
    • Loop body with some way to change the test condition
  • There are three loop statements in C++:
    • for
    • while
    • do...while
  • We will start with the simplest of the three -- the while statement

4.4.2: Coding while Statements

  • The simplest looping structure is the while statement
  • A while statement has a test condition and a body, like an if statement
  • Before each execution of the loop body, the while statement checks the test condition
  • If the test condition evaluates to true, then our program executes the body of the loop
  • Syntax:
    while (test) {
       statement1
       statement2
       ...
    }
    
  • Where:
    • test: the test condition to evaluate
    • statementX: the statements to execute while the test remains true
  • For example:
    string repeat = "y";
    while ("y" == repeat) {
        // ... statements to repeat
        cin >> repeat;
    }
    
  • The following flow chart shows how the while loop operates
  • We will explore the while loop in the next exercise

Diagram of while Loop Operation

While loop flow chart

4.4.3: Understanding the while Loop

  • The following looping application simulates the play of an exciting game
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main() {
    string repeat = "y";
    while ("y" == repeat) {
        cout << "\nPlaying an exciting game!\n";
        cout << "Do you want to play again? (y/n) ";
        cin >> repeat;
    }
    cout << "\nThanks for playing!\n";

    return 0;
}
  • Notice the structure of the code for the looping application
  • First was the statement to correctly initialize the looping condition:
    string repeat = "y";
  • Then came the while statement with the test condition
    while ("y" == repeat)
  • The loop executes the body of the loop if and only if the condition evaluates to true
  • Another important part of the loop is the statement:
    cin >> repeat;
  • Most loops have these parts:
    • Initialization code
    • Loop test condition
    • Loop body with some way to change the test condition

Formatting the Code

  • It is important to format the loop code correctly:
    string repeat = "y";
    while ("y" == repeat) {
        // ... statements to repeat
        cin >> repeat;
    }
    
  • Note how the repeated code is indented inside the loop
  • This lets us see easily which code is repeated and which is not
  • Also note the placement of curly braces
  • Different groups have different practices for placing curly braces in a loop statement
  • For the acceptable styles for this course see: Curly Braces

Exercise 4.4

In this exercise we use a loop to allow a user to repeat a program.

Specifications

  1. Start with your final code from the last exercise and save a copy of it as loopy.cpp.
  2. Add the following code after the statement int guess = 0; and before the cout statement:
    string repeat = "y";
    

    This is the initialization code that we will use for the test condition that comes next.

  3. We want to repeat all the rest of the code in our program. For this we need to add a while statement such as:
    while ("y" == repeat) {
        // Place all the rest of the code after the
        // initialization between these curly braces.
    }
    

    Statements inside the curly braces repeat while the test condition in the parenthesis, ("y" == repeat), evaluates to true. For more information, see section: 4.4.2: Coding while Statements.

  4. Inside the while loop we need some way to change the test condition. We change the test condition by letting the user enter a value for the repeat variable by adding the following code at the end of the loop just before the closing curly brace:
    cout << "\nDo you want to play again? (y/n) ";
    cin >> repeat;
    

    Without these two statements our loop would have no way to exit. A loop with no way to exit is known as an infinite loop. For more information, see section: 4.4.3: Understanding the while Loop.

  5. Formatting a loop is important. Indent all the code within the curly braces of the while loop. For more information, see Formatting the Code in the section: 4.4.3: Understanding the while Loop.
  6. As a final part of our program, we add the infamous phrase: "Game Over". Add the following statement after the closing curly brace of the while loop:
    cout << "Game over\n";
    
  7. Compile and run your program again and verify the output looks like:
    I'm thinking of a number between 1 and 10.
    Can you guess it?
    
    Enter your guess: 3
    You entered: 3
    Sorry, that is not correct.
    
    Do you want to play again? (y/n) y
    I'm thinking of a number between 1 and 10.
    Can you guess it?
    
    Enter your guess: 7
    You entered: 7
    *** Correct! ***
    
    Do you want to play again? (y/n) n
    Game over
    
  8. Submit your program source code to Blackboard as part of assignment 4.

Completed Program

When finished, your application should look like the following. Note especially the extra indentation within the curly braces of the while loop.

Completed exercise

Check Yourself

As time permits, be prepared to answer these questions. You can find more information by following the links after the question.

  1. What is the purpose of a loop? (4.4.1)
  2. What are the three parts of any loop? (4.4.1)
  3. What is the syntax of a while statement? (4.4.2)
  4. What is the purpose of a loop test condition? (4.4.3)
  5. What is the purpose of loop initialization code? (4.4.3)
  6. What part of a loop is repeated? (4.4.3)
  7. What is meant by the term main programming loop? (4.4.4)

4.4.4: Generalizing the Main Loop

  • We can generalize the main loop of our example
  • Implementation can be different from one program to another
  • However, the basic structure is the same for most programs

Program Flow with a Main Loop

Main loop flow

Notes on the Program Flow

  • Set Up (statements before the loop)
    • Declare and initialize variables
    • Provide instructions
  • Repeated steps (loop body)
    • Get User Input
    • Update Variables
    • Update Display
    • Program Done?
      • Check if the program is completed
      • Often the user decides to exit
      • Change variables in the test condition of the loop
  • Shut Down (statements after the loop)
    • Provide the user any final information
    • End the program

4.4.5: Common Loop Pitfalls

  • Loops have many pitfalls for the unwary
  • The following are the most common problems you should look out for

Infinite Loops

  • Common error: unintentional infinite loop
  • For example, what is wrong with the following code?
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main() {
    string repeat = "y";
    while ("y" == repeat) {
        cout << "\nPlaying an exciting game!\n";
        cout << "Do you want to play again? (y/n) ";
    }
    cout << "\nThanks for playing!\n";

    return 0;
}

Missing Curly Braces

  • Technically, the while loop executes a single statement after the parenthesis of the test condition
  • However, we usually use curly braces { } to expand the single statement
  • The curly braces let us put multiple statements in them
  • For example, what is wrong with the following code?
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main() {
    string repeat = "y";
    while ("y" == repeat)
        cout << "\nPlaying an exciting game!\n";
        cout << "Do you want to play again? (y/n) ";
        cin >> repeat;
    cout << "\nThanks for playing!\n";

    return 0;
}

Empty Statements

  • Remember that statements are terminated by a semicolon
  • Is the following a legal statement?
    ;
  • This is known as an empty or null statement
  • Empty statements are a common source of infinite loops
  • For example, what is wrong with the following code?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main() {
    string repeat = "y";
    while ("y" == repeat); {
        cout << "\nPlaying an exciting game!\n";
        cout << "Do you want to play again? (y/n) ";
        cin >> repeat;
    }
    cout << "\nThanks for playing!\n";

    return 0;
}

4.4.6: Summary

  • Loops execute a block of code repeatedly
  • To stop (terminate) a loop you set a test condition
  • General loop structure:
    • Initialization code
    • Test condition -- evaluated during the loop
    • Loop body with some way to change the test condition
  • One loop statement we looked at is the while loop
  • For example:
    string repeat = "y";
    while ("y" == repeat) {
        // ... statements to repeat
        cin >> repeat;
    }
    
  • Most programs have a main loop
  • Statements inside the loop repeat until the program exits
  • Several problems can occur when using a loop including:
    • Infinite loops: loops that "never" end
    • Missing curly braces
    • Empty statements

Wrap Up

Due Next:
A3-Drawing with Turtles (3/5/09)
A4-Select a Shape (3/12/09)
  • When class is over, please shut down your computer
  • You may complete unfinished exercises at the end of the class or at any time before the next class.
Home | Blackboard | Announcements | Day Schedule | Eve Schedule
Course info | Help | FAQ's | HowTo's | Links
Last Updated: March 22 2009 @14:39:12