3. Arithmetic, Strings and Objects

What We Will Cover


Continuations

Questions from last class?

Homework Questions?

Homework Discussion Questions

  1. What was the hardest part of writing the code to implement your algorithm?
  2. How useful was the example executable file for determining how the program operated?
  3. What solution did you come up with to make sure you had no tab characters in your source code?
  4. How did you keep the line length to 80 characters or less?
  5. What was the hardest CodeLab tutorial exercise? easiest?

Quiz

Compiling and Running a Program Using TextPad

  • Many text editors have provision for compiling within the editor
  • We use TextPad in our class room as a text editor
  • Note that you can install TextPad at home
  • To make your in-class exercises easier, we have set up TextPad to compile and run C++ programs
  • We will use the following program for demonstration
  • 1
    2
    3
    4
    5
    6
    7
    
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    }
    

Compiling with TextPad

  1. Load your source code into the active TextPad window
  2. Select the Tools menu
  3. Select Compile C++
  4. If there are any syntax errors, you will see a page or area showing them
  5. Otherwise, you will return to your source code page

Running Programs with TextPad

  1. Load your source code into the active TextPad window
  2. Select the Tools menu
  3. Select Run C++ Application
  4. Your program will run in a console window

3.1: Numbers and Arithmetic

Learner Outcomes

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

  • Distinguish between an integer and a floating-point number
  • Write C++ code for arithmetic expressions
  • Infer the type returned from a mixed-mode arithmetic expression
  • Construct expressions that use mathematical functions

3.1.1: Algorithms Using Numbers and Arithmetic

  • Many problems can be solved using mathematical formulas and numbers
  • Consider the simple problem of adding up all the coins in your pocket to get the total value in dollars
  • What would be an algorithm for solving this problem?
  • To implement this algorithm, we will need to use numbers and arithmetic
  • As we saw before, C++ has two general types of numbers: integers and floating-point
  • An integer is zero or any positive or negative number without a decimal point
  • For example:
    0   1   -1    +5    -27   1000    -128
  • We call numbers like these literal integers because they stand for what they look like
  • A floating-point number is any signed or unsigned number with a decimal point
  • For example:
    0.0   1.0   -1.1   +5.   -6.3    3234.56    0.33
  • Note that 0.0, 1.0 and +5. are floating-point numbers, but could be rewritten as integers
  • In C++, both integers and floating-point numbers cannot have any commas or special symbols
  • The following program implements an algorithm for summing coins
  • Which characters are integers and which are floating-point numbers?

Program coins.cpp to Sum Coins

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

int main() {
    int pennies = 8;
    int nickels = 5;
    int dimes = 4;
    int quarters = 3;

    double total = pennies * 0.01 + nickels * .05
        + dimes * 0.10 + quarters * 0.25;

    cout << "Total value = " << total << "\n";

    return 0;
}

3.1.2: Arithmetic

  • C++ uses the following operators for arithmetic:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder)
  • As in algebra, multiplication and division are performed before addition and subtraction
  • To change the order of operation, you use parentheses
  • For example:

    a + b / 2 is written as: a + b / 2

    (a + b) / 2 is written as: (a + b) / 2

Notes About Arithmetic

  1. You can use parentheses to group expressions
    • Anything within the parentheses is evaluated first
    • 2 * (10 + 5)
  2. You can have parentheses within parentheses
    • Innermost parenthesis evaluated first
    • (2 * (10 + 5))
  3. Parentheses cannot be used to indicate multiplication
    • Invalid expression: (2)(3)
    • Must use the * operator

Programming Style

  • Programming style: add spaces around binary operators
    • 2 + 3, not 2+3
  • Programming style: no spacing after opening or before closing parenthesis
    • (2 / 3), not ( 2/3 )

We explore how you can use numbers and arithmetic in the following exercise.

Exercise 3.1

Through the miracles of computer science, we will now convert your $1000 computer into a $10 calculator! Along the way, we learn how to work with arithmetic using C++.

Specifications

  1. Copy the following program into a text editor, save it as arithmetic.cpp, and then compile and run the starter program to make sure you copied it correctly.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. In main(), declare two double variables named a and b, and assign them a value of 7 and 2 respectively. For instance:
    double a = 7, b = 2;
  3. Add a line of code to display the arithmetic expression (a + b) and then recompile and run the program.
    cout << "a + b = " << a + b << endl;
    

    The output when you run the program should look like this:

    a + b = 9
    

    If you do not see this output, please ask a classmate or the instructor for help.

  4. Add three more lines of code like the previous one that computes the expressions: a - b, a * b and a / b. Compile and run your program again and make sure your program now displays the following output:
    a + b = 9
    a - b = 5
    a * b = 14
    a / b = 3.5
    
  5. The order of operations matters in C++ just like it does in algebra. Multiplication and division are performed before addition and subtraction. Add the following two statements to your program:
    cout << "a + b / 2 = " << a + b / 2 << endl;
    cout << "(a + b) / 2 = " << (a + b) / 2 << endl;
    
  6. Compile and run your program again and compare the output. Your program should now display the following output:
    a + b = 9
    a - b = 5
    a * b = 14
    a / b = 3.5
    a + b / 2 = 8
    (a + b) / 2 = 4.5
    

    Note how the output of the two statements is different. You can change the order of operation using parenthesis, just like in algebra. For more information on the order of operations see section: 3.1.2: Arithmetic.

    As you can see, arithmetic in C++ works much like you would expect. However, there are some mysteries when working with integer variables which we will now explore:

    • Truncation in integer division
    • Modulus (%) operator

  7. Truncation in integer division: Change the data type of the two variables from double to int, like this:
    int a = 7, b = 2;
  8. Compile and run your program again and compare the output. Note how the result of the division operation changed. What happened to the decimal part of the result?

    In programming terms, we say that the decimal part is truncated (cut short). You have to watch out for this in C++ programming or you may get unexpected results in your calculations. For more information see section: 3.1.4: Integer Division and Modulus.

  9. Modulus (%) operator: Sometimes we want the integer remainder from an integer division. To see the integer remainder, we use the modulus (%) operator. Add the following statement to your program:
    cout << "a % b = " << a % b << endl;
    
  10. Compile and run your program again with this added statement. Your program should now display the following output:
    a + b = 9
    a - b = 5
    a * b = 14
    a / b = 3
    a + b / 2 = 8
    (a + b) / 2 = 4
    a % b = 1
    

    For more information on the modulus operator see section: 3.1.4: Integer Division and Modulus.

  11. Mathematical functions: More complex mathematical operations require the use of a function in C++. one such function is sqrt(number) which calculates the square root of the number inside the parenthesis. Add the following statement to your program:
    cout << "sqrt(a + b) = " << sqrt(a + b) << endl;
    
  12. You program will not compile with this new statement because you must include a library of the mathematical functions. Add the statement: #include <cmath> to the top of your program like this:
    #include <iostream>
    #include <cmath> // math function library
    using namespace std;
    
  13. Compile and run your program again with this added statement. Your program should now compile and display the following output when run:
    a + b = 9
    a - b = 5
    a * b = 14
    a / b = 3
    a + b / 2 = 8
    (a + b) / 2 = 4
    a % b = 1
    sqrt(a + b) = 3
    

    For more information on mathematical functions see section: 3.1.5: Mathematical Functions.

  14. Submit your program source code that displays all eight (8) expressions to Blackboard as part of assignment 3.

Completed Program

Once you are finished, your source code should look like the following:

Listing of arithmetic.cpp

Check Yourself

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. How can you tell the difference between an integer and a floating-point number? (3.1.1)
  2. What are the five operators C++ provides for arithmetic? (3.1.2)
  3. What is the first operation performed in the expression: 1 + 2 * 3 / 4 % 5? (3.1.2)
  4. What is the data type returned by the following expression? (3.1.3)
    3 + 4.5
  5. What happens to the remainder during integer division? (3.1.4)
  6. What operator can you use to compute the integer remainder? (3.1.4)
  7. What is the result of the following arithmetic expressions? (3.1.4)
    5 / 4
    5 % 4
    
  8. What is a function? (3.1.5)
  9. What code do you write to calculate the square root of the number 49? (3.1.5)

3.1.3: Mixed-Mode Expressions

  • Recall that different data types are stored in different forms
    • An int is stored in 4 bytes
    • A double is stored in 8 bytes
    • The format they are stored in is different as well
  • The computer needs both operands in the same form before it can perform an operation
  • If one operand is different than the other, the compiler converts it to the wider of the two types
  • For example:
    2 + 2.3
  • First number (2) is an int
  • Second number (2.3) is a double
  • C++ will automatically convert and int to a double
  • Then the arithmetic operation can take place to produce a result of 4.3
  • Remember that the result of arithmetic with an int and a double is a double

3.1.4: Integer Division and Modulus

  • Dividing two integers can produce unexpected results for the unwary
  • In division, if at least one of the numbers is a floating-point number, the result is a floating point number:
    7.0 / 2.0   // 3.4
    7 / 2.0     // 3.4
    7.0 / 2     // 3.4
    
  • However, if both numbers are integers, then the result is an integer:
    7 / 2       // 3
    
  • The decimal remainder is truncated (cut short, discarded, thrown away)
  • To get the integer remainder of division between two integers, you use the modulus operator: %
    7 % 2       // 1 (remainder)
    
  • 7 % 2 returns 1 because 1 is the remainder when 7 is divided by 2
  •     3  r 1
    2 ) 7
       -6
        1 remainder
    
  • For a refresher on remainders see: Long Division with Remainders

Check Yourself

What is the result of the following arithmetic operations?

  • 9 / 4
  • 17 / 3
  • 14 / 2
  • 9 % 4
  • 17 % 3
  • 14 % 2

3.1.5: Mathematical Functions

  • Operators provide only the simplest mathematical operations
  • For more complex operations, we use mathematical functions
  • A C++ function is like a mathematical function that takes an argument ("input") and produces ("returns") a value
  • For example:
    cout << sqrt(9.0) << endl;
  • In the above example, the input is 9.0 and the sqrt() function returns the square root of the argument
  • C++ has a standard library named cmath that contains many such functions
Name Description Example Result
fabs absolute value fabs(-3.9)
fabs(3.9)
3.9
3.9
exp exponent (ex) exp(1.0) 2.71828
log natural log log(10.0) 3.10259
pow powers (xy) pow(2.0, 3.0) 8
sqrt square root sqrt(4.0) 2
sin sine sin(0) 0
cos cosine cos(0) 1
  • In addition, it includes two similar functions: ceil, and floor
Name Description Example Result
ceil ceiling: round up ceil(3.3)
ceil(3.7)
4
4
floor floor: round down floor(3.3)
floor(3.7)
3
3
  • Both return whole numbers, although they are of type double

Using Mathematical Functions

  • How are mathematical functions evaluated?
  • Whatever is within the parenthesis of the function call is evaluated first
  • Thus, in the following example, we get the square root of 9.0
  • cout << sqrt(3.0 * 3) << endl;
  • If the function is used in an arithmetic expression, they are handled just like a number of the type returned
  • For example, in the following, the value 4.0 is stored in the double variable num:
  • double num = 1 + sqrt(3.0 * 3.0);
    cout << num << endl;
    
  • Note that the function evaluates the sqrt(3.0 * 3) before adding it to 1.0
  • Thus functions have a higher precedence than arithmetic operators

3.1.6: Summary

  • C++ uses the following operators for arithmetic:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder)
  • As in algebra, multiplication and division are performed before addition and subtraction
  • To change the order of operation, you use parenthesis
  • The results of integer division are truncated
  • You must use modulus operator (%) to get the remainder value
  • More complex mathematical operations are available using the cmath library
  • cout << sqrt(3.0 * 3) << endl;

3.2: Strings and Characters

Learner Outcomes

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

  • Identify characters and strings from their literal representation
  • Assign characters and strings to variables
  • Concatenate strings
  • Collect characters and strings from user input
  • Output characters and strings

3.2.1: Introduction to Strings

  • Oftentimes we need to work with text data to solve problems
  • For example, we may want to output some literal text to a console window as output:
    cout << "Hello World!" << endl;
  • Programmers refer to text like this as a string because it is composed of a sequence of characters that we string together
  • C++ provides the string type so we can work with text
  • The string type is defined in the library for strings: #include <string>
  • This library is included automatically with our version of g++
  • Strings are enclosed in double quotes, which are not part of the string
  • For example:
    "Hello"  "b"  "3.14159"  "$3.95"  "My name is Ed"
  • Notice that the string "3.14159" could be expressed as a double by removing the quotes
  • However, a computer stores these two values very differently and we must use them in different ways
  • For instance, we cannot multiply the "3.14159" by 2, but we can when it is expressed as a double:
    cout << "3.14159" * 2; // NO!
    cout << 3.14159 * 2; // allowed
    

3.2.2: String Variables and Simple I/O

  • We declare and assign values to string variables like numeric types
  • For example:
    string firstName;             // declaration
    firstName = "Edward";         // assignment
    string lastName = "Parrish";  // declaration + assignment
    cout << firstName << " " << lastName << endl;
    

Simple I/O with Strings

  • Like numbers, you can output type string using cout <<
  • Also, you can input a string using cin >> stringName
  • For example:
    string name;
    cout << "Enter your name: ";
    cin >> name;
    cout << "You entered: " << name  << endl;
    
  • The cin statement assigns the user input to the string variable name

3.2.3: Joining Strings (Concatenation)

  • You can join two strings together using the '+' operator
  • The join operation is called concatenation
  • For example:
    string s1 = "Hello", s2 = "World!";
    string s3 = s1 + s2;
    cout << s3 << endl;
    
  • The string s3 now has the contents of both s1 and s2
  • You can also mix string variables and literal strings
  • string s1 = "Hello", s2 = "World!";
    string s3 = s1 + ", " + s2;
    cout << s3 << endl;
    
  • One or both strings surrounding the + must be a string variable
  • For instance, the following will NOT work:
    string greeting = "Hello" + " " + "World!"; // No!
    
  • However, this is not usually a problem because we can just make one long literal string:
    string greeting = "Hello World!";
    

3.2.4: Output of Hard-to-Print Characters

  • We have been using the << operator to output strings
  • string msg = "Hello Mom!";
    cout << msg << endl;
    
  • However, some characters are more difficult to output than others
  • For example, what would the compiler do with the following statement?
  • cout << "Say, "Hey!"" << endl;
  • Some characters cannot be output directly in a string
  • Also, the first 32 ASCII characters are not visible on our monitors
    • Known as control codes because they control the output device
  • Even though these characters are not visible, we sometimes need to use them
    • For example, a newline character
  • We need some way to "print" invisible and hard-to-print characters

Escape Sequences

  • C++ can access control codes and hard-to-print characters using escape sequences
  • Backslash (\) directly in front of a certain character tells the compiler to escape from the normal interpretation
  • The following table has some nonprinting and hard-to-print characters:
Sequence Meaning
\a Alert (sound alert noise)
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quote
\" Double quote
\ooo ASCII character in octal notation
\xhhh ASCII character in hexadecimal notation
  • Some examples:
    cout << '\a' << endl; // alert
    cout << '\n' << endl;
    cout << "Left \t Right" << endl;
    cout << "one\ntwo\nthree" << endl;
    

Programming Style

We explore how you can use strings in the next exercise.

Exercise 3.2

In this exercise we write an interactive program using strings that runs like this:

First name: Ed
Last name: Parrish
Welcome "Ed Parrish"!
Enter your message: Never give up
Your message: "Never give up"

Note that the underlined font shows what is typed by the user. As you work through the exercise, I suggest that you compile after each step so you know where the error is located if you make a mistake. Also, if you get stuck then ask a classmate or the instructor for help.

Specifications

  1. Copy the following program into a text editor, save it as nameapp.cpp, and then compile and run the starter program to make sure you copied it correctly.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. In main(), declare three string variables: firstName, lastName, fullName
    string firstName, lastName, fullName;
  3. Add two statements: (1) to prompt the user for the data they should enter and (2) to collect the user input and store it in the firstName variable. For instance:
    cout << "First name: ";
    cin >> firstName;
    
  4. Add two more statements like these to collect the last name and store the input in the lastName variable.
  5. Write a line of code to concatenate (join) the first and last names and assign them to the variable fullName like this:
    fullName = firstName + " " + lastName;

    For more information see section: 3.2.3: Joining Strings (Concatenation)

  6. Finally, add code to your program to output the fullName variable using cout:
    cout << "Full name: " << fullName << "!\n";
    
  7. Compile and run your program to make sure it works correctly like this:
    First name: Ed
    Last name: Parrish
    Full name: Ed Parrish!
    
  8. Some text characters are hard to print, like a double quote ("). To print these we must escape them from their special meaning by putting a backslash (\) in front of them. Put a double quote mark around the full name by changing the line printing the full name to:
    cout << "Welcome \"" << fullName << "\"!\n";
    

    For more information on escaping characters see section: 3.2.4: Output of Hard-to-Print Characters

  9. To enter an entire line of text, you need to use the getline() function. See section 3.2.5: String Input With Spaces for an explanation. Let us use getline() to enter a message in our program by adding the following lines after the greeting:
    string message;
    cout << "Enter your message: ";
    cin >> ws;
    getline(cin, message);
    cout << "Your message: \"" << message << "\"\n";
    
  10. Compile and run your program to make sure it works correctly like this:
    First name: Ed
    Last name: Parrish
    Welcome "Ed Parrish"!
    Enter your message: Never give up!
    Your message: "Never give up!"
    
  11. Submit your program source code to Blackboard as part of assignment 3.

Completed Program

Once you are finished, your source code should look like the following:

Listing of nameapp.cpp

Check Yourself

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. What type of delimiters are used to enclose strings? (3.2.1)
  2. What code do you write to define a string variable named myString and assign it a value of, "Hi Mom!"? (3.2.2)
  3. What code do you write to input a word from the keyboard and store it in a variable named myWord? (3.2.2)
  4. What operator is used to join two strings? (3.2.3)
  5. Certain characters like double-quote marks (") are hard to print. How do you output these characters in C++? (3.2.4)
  6. What is the escape sequence for a newline? (3.2.4)
  7. How many words can you enter with the following code? (3.2.5)
    string something;
    cout << "Enter something: ";
    cin >> something;
    cout << "You entered: " << something << endl;
    
  8. How can you change the previous code to read a string that includes spaces? (3.2.5)
  9. What code can you use to clear newlines and other whitespace from the input stream? (3.2.5)
  10. What type of delimiters are used to enclose single characters of type char? (3.2.6)
  11. Are "A" and 'A' the same? Why or why not? (3.2.6)
  12. When would you want to use a char variable rather than a string variable? (3.2.6)
  13. What code do you write to declare a char variable named myChar and assign it a value of 'A'? (3.2.6)
  14. What code do you write to input a single character from the keyboard and store it in a variable named myChar? (3.2.6)

3.2.5: String Input With Spaces

  • We have been using the >> operator to enter data into a string variable
  • string something;
    cout << "Enter something: ";
    cin >> something;
    cout << "You entered: " << something << endl;
    
  • However, there are some complications
  • >> skips whitespace and stops on encountering more whitespace
  • Thus, we only get a single word for each input variable
  • If a user types in "Hello Mom!", we would only read "Hello" and not " Mom!"
  • This is because cin >> s1 works as follows:
    1. Skips whitespace
    2. Reads non-whitespace characters into the variable
    3. Stops reading when whitespace is found

Input Using getline()

  • To read an entire line we use function getline()
  • Syntax:
    getline(cin, stringVariable);
    
  • Where:
    • stringVariable: the name of the string variable
  • For example:
    string line;
    cout << "Enter a line of input:\n";
    getline(cin, line);
    cout << line << "END OF OUTPUT\n";
    
  • Note that getline() stops reading when it encounters a '\n'

The Problem with Newlines

  • When you press the Enter key, a newline character ('\n') is inserted as part of the input
  • The newline character can cause problems when you mix cin >> with getline()
  • Recall that cin >> s1:
    1. Skips whitespace
    2. Reads non-whitespace characters into the variable
    3. Stops reading when whitespace is found
  • Since whitespace includes newline characters, using cin >> will leave a newline character in the input stream
  • However, getline() just stops reading when it first finds a newline character
  • This can lead to mysterious results in code like the following:
    cout << "Enter your age: ";
    int age;
    cin >> age;
    cout << "Enter your full name: ";
    string name;
    getline(cin, name);
    cout << "Your age: " << age << endl
         << "Your full name: " << name << endl;
    
  • To get around this problem you can use cin >> ws just before getline()
    cin >> ws; // clear whitespace from buffer
    
  • You can see how to use this fix in the following example

Example Using cin >> ws

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

int main() {
    cout << "Enter your age: ";
    int age;
    cin >> age;
    cout << "Enter your full name: ";
    string name;
    cin >> ws; // clear whitespace from buffer
    getline(cin, name);
    cout << "Your age: " << age << endl
         << "Your full name: " << name << endl;
}

3.2.6: Type char

  • A character is a single letter, number or special symbol
  • You specify a character by enclosing it in single quotes (')
    • The quote marks are not part of the data
  • For example:
    'a'   'b'   'Z'   '3'   'q'   '$'   '*'
  • C++ provides the char data type to store characters
  • By contrast, a string always uses more than one byte, even for a single character, so it can keep track of potentially multiple characters
  • When you use a char data type, you store the character using an ASCII code
  • ASCII is a coding method that assigns a number to every character
  • You can see the codes in an ASCII Table

Declaring and Assigning char Variables

  • As with other data types, you must declare char variables before use:
    char letter;
  • You assign values to a char variable using the equals sign:
    letter = 'A';
  • Just like numbers, you can combine declaration and assignment into one statement:
    char letter = 'A';
  • Also, you can declare multiple variables one line:
    char letter, letterA = 'A', letterB = 'B';

User I/O with Type char

  • Like numbers, you can output type char using cout <<
    char letter = 'A';
    cout << letter << 'B' << endl;
    
  • Also, you can input type char using cin >>
    cin >> letter;
    cout << letter  << endl;
    

3.2.7: Summary

  • You make string literals by enclosing characters in double quotes
  • You declare string variables using string as the data type
  • string s1 = "Hello Mom!";
  • You use functions of the string object for some operations
  • To concatenate two strings, use the "+" operator:
    string s2 = s1 + " suffix";
  • Type string can be input and output with cin and cout
  • To read an entire line, you need to use the getline() function
  • getline(cin, line);
  • Sometimes cin >> can leave a '\n' character in the input stream
  • To get around this problem you can use cin >> ws before getline()
    cin >> ws; // clear whitespace from buffer
    
  • A character is a letter, number or special symbol
  • You make character literals by enclosing a single character in single quotes
  • You declare character variables using char as the data type
  • char letter = 'A';
    
  • You can input and output char data using cin and cout like integer data types

3.3: Objects and Turtles

Learner Outcomes

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

  • Construct objects and supply initial values
  • Use member functions and the dot notation
  • Modify and query the state of an object through member functions
  • Work with the Time class provided by the textbook

3.3.1: Introduction to Classes, Objects and Turtles

  • As programs gets more complex, you need a way to organize the code
  • In C++, one way to organize complex code is to use objects and classes
  • An object is a collection of variables that can be used in certain ways
  • A class is a set of rules that describes how an object can behave
  • For instance, string is a class type that organizes sequences of characters
  • When a programmer declares a class, he or she is developing a new data type
    • By contrast, types like int and double were developed by the designers of the C/C++ language
  • With a class declared, we can create objects and then issue commands to the object
  • We will discuss how to create our own classes later in the course
  • To start with, we will use classes developed by other programmers

Turtle Graphics

  • As an example of using classes and objects developed by other programmers, let us consider Myrtle the turtle
  • Myrtle the turtle lives in a small world about the size of a computer window
  • Myrtle spends most of her time sleeping, which is not very interesting
  • So when I want to liven things up, I attach a pen to her tail *
  • Some of the pictures that Myrtle makes as she crawls around are quite interesting
  • In fact, Myrtle is quite an artist
  • Below is an example of Myrtle drawing an "M" (for Myrtle)

Myrtle Drawing an "M"

Turtle drawing an M

* Note: no animals were harmed in creating this example. Honest!

3.3.2: Including Turtle Graphics

  • We create drawings with a turtle like Myrtle using a turtle graphics library
  • Turtle graphics are a graphics library for displaying shapes in a graphics window
  • A window is a rectangular area of the computer screen suitable for displaying graphics
  • A graphics window is different than the console we have used with our programs so far
  • To make use of turtle graphics, we must make a few changes to our code and compile it differently than a console application
  • First of all, we need to include the turtle graphics library:
    #include "turtlelib.cpp"
  • We use " " instead of < > because the file is not a standard library
  • Also, we must change the main() function to ccc_win_main() as shown in the example below
  • The ccc part of the name stands for Computing Concepts with C++ Essentials
  • Normally we do not use #include with .cpp files
  • However, including a .cpp file keeps things simpler for now

Example Program for Drawing an "M": turtlem.cpp

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

int ccc_win_main() {
    Turtle myrtle;
    myrtle.moveTo(-7, 5);
    myrtle.forward(3);
    myrtle.right(135);
    myrtle.forward(1.5);
    myrtle.left(90);
    myrtle.forward(1.5);
    myrtle.right(135);
    myrtle.forward(3);

    return 0;
}

3.3.3: Constructing Objects

  • Whenever we create an object from a class, we call it "constructing an object"
  • We construct an object like we create variables
  • The syntax is:
    ClassName objectName;
    or
    ClassName objectName(arguments);
    
  • Where:
    • ClassName: the name of the class type
    • objectName: the variable of the class type
    • arguments: one or more arguments inside parenthesis
  • For example:
    Turtle myrtle;
    Turtle boggy(-7, 5);
    
  • However, you have to be careful because the shortcut is not completely consistent
  • When you create an object with no parameters, you must remember to NOT use any parenthesis
    Turtle myrtle; // constructs a Turtle object
    Turtle boggy(); // NO!
    
  • Unfortunately, the compiler will not catch the problem with the boggy() object
  • The reason is that Turtle boggy(); is a valid statement in C++ called a function prototype
  • We will discuss functions and prototypes later in the course
  • In any case, you must remember to NOT use parenthesis when using the shortcut method of default construction

3.3.4: Using Objects

  • Once we construct an object we can manipulate it using its member functions
  • A function applied to an object with the dot notation is called a member function
  • Syntax:
    objectName.functionName(arguments)
  • Where:
    • objectName: the variable of the class type
    • functionName: the name of the function we want to call
    • arguments: zero or more arguments inside parenthesis
  • For example, the Turtle class has several member functions used to manipulate the turtle
  • One such member function is: forward()
  • The forward() function tells the turtle to move forward
  • myrtle.forward(3);
  • Note that the turtle normally leaves a trail behind it when it moves

Turning the Turtle

  • You can tell a turtle to move in a different direction by changing its heading
  • The right() function tells the turtle to turn right some number of degrees from its current heading
  • For example:
    myrtle.right(135);
  • Similarly, the left() function tells the turtle to turn to the left
  • myrtle.left(90);
  • All turns are from the perspective of the turtle

    Turtle turns

  • The following are some commonly used functions of the Turtle class

Some Commonly Used Functions of the Turtle Class

Function Action Taken
forward(amount) Move the turtle forward the given amount in the direction it is heading.
left(degrees) Turn the turtle to the left (counter-clockwise) the given number of degrees from the current direction it is heading.
right(degrees) Turn the turtle to the right (clockwise) the given number of degrees from the current direction it is heading.
moveTo(x, y) Move the turtle to the specified x, y coordinates.

3.3.5: Compiling Code That Includes Graphics

  • Since graphics libraries are not part of standard C++, we have to tell the compiler where to find any graphics library files we use
  • The classroom and lab computers are set up so that TextPad knows where the graphics classes are located
  • To compile, you simply select the menu item for compiling C++ graphics
  • You can set up TextPad at home to work the same way by following my instructions: How To Setup TextPad for Writing C++ Programs
  • However, if you prefer to work at the command line, or are using a Mac OSX or Linux computer, you will need a different technique

Working at the Command Line

  • One technique is to work at the command line
  • The easiest way to make use of the graphics files is to copy them to the same directory as you are working within
  • That way the #include directive will find the files when it compiles your code
  • The graphics files are all located in: cccfiles.zip
  • The following instructions explain how to download and install on Windows and Linux/Unix/Mac OS X
  • To run graphics files on Linux/Unix/Mac OS X, you will need to open an X11 terminal

Working at the Command Line on Windows

Note : these instructions assume you installed Cygwin following my instructions.

  1. Save cccfiles.zip to a convenient location on your computer like the Desktop or your Cygwin home directory
  2. Open the ZIP file by double clicking on the file, which will open a new window.
  3. Select all the files in the window and copy them into the directory in which you are working.
  4. Copy the following command string to the Cygwin command prompt and change the file names to match your source and executable file names:

    g++ -D CCC_MSW -I c:\cygwin\usr\include\w32api -o executableName sourceFile.cpp ccc_msw.cpp ccc_shap.cpp -luser32 -lgdi32

    Where:
    • executableName: the name of the executable file you want to create
    • sourceFile.cpp: the name of your source code file.
  5. Run your program in the usual way:

    ./executableName

Working at the Command Line on Linux/Unix/Mac OS X

Note: the following instructions assume you have installed g++ and X11.

  1. Save cccfiles.zip to a convenient location on your computer like the Desktop or your home directory
  2. Open the ZIP file by double clicking on the file, which will open a new window.
  3. Select all the files in the window and copy them into the directory in which you are working.
  4. Open a terminal window.
  5. Copy the following command string to the command prompt and change the file names to match your source and executable file names:

    g++ -o executableName sourceFile.cpp ccc_x11.cpp ccc_shap.cpp -L/usr/X11R6/lib -lX11

    Where:
    • executableName: the name of the executable file you want to create
    • sourceFile.cpp: the name of your source code file.
  6. Run your program in the usual way:

    ./executableName

More Information

Exercise 3.3: The Art of Programming!

In this exercise we look at how to draw a simple shape using turtle graphics.

Specifications

  1. Copy the following program into a text editor, save it as square.cpp, and then compile and run the starter program to make sure you copied it correctly and know how to compile turtle graphics.
    #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 myTurtle = Turtle();

    For more information on constructing objects see section: 3.3.3: Constructing Objects Without Parameters

  3. Let us use the object we created to draw a line. Add the following command after the object you constructed in the previous step:
    myTurtle.forward(5);
    
  4. Compile and execute the code and verify you see a line in a window.

    If you encounter any syntax errors, or do not see the line, correct your errors or get help from a classmate or the instructor.

  5. Now add code to draw the rest of the square by adding the following commands:
    myTurtle.right(90);
    myTurtle.forward(5);
    myTurtle.right(90);
    myTurtle.forward(5);
    myTurtle.right(90);
    myTurtle.forward(5);
    myTurtle.right(90);
    

    For more information on drawing see section: 3.3.4: Using Objects

  6. Compile and execute the code and verify you see a square in a window.

    If you encounter any syntax errors, or do not see the square, correct your errors or get help from a classmate or the instructor.

  7. Submit your "square.cpp" source code to Blackboard as part of assignment 3.

    Note: you are welcome to draw more shapes.

Check Yourself

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. What is an object? (3.3.1)
  2. What is a class? (3.3.1)
  3. Why do programmers write classes? (3.3.1)
  4. What library do you include to use turtle graphics? (3.3.2)
  5. What is the name of the main function you use for turtle graphics? (3.3.2)
  6. What code do you write to construct a Turtle object named "boggy"? (3.3.3)
  7. What does the following code do? (3.3.4)
    boggy.forward(5);
  8. For the turtle named "boggy", what command do you write to turn clockwise by 90 degrees? (3.3.4)
  9. What TextPad tool do you run to compile programs using turtle graphics? (3.3.5)
  10. Where can you find the instructions for setting up TextPad to compile turtle graphics? (3.3.5)
  11. If you do not have TextPad setup to compile graphics, how can you compile programs? (3.3.5)
  12. What does the following code do? (3.3.6)
    boggy.setHeading(90);
  13. How can you look up the commands of the Turtle class? (3.3.7)

3.3.6: More Turtle Capabilities

  • Sometimes you want to move a turtle without drawing
  • To do this, you can use the setPenDown() function
    myrtle.setPenDown(false); // stops drawing
    
  • Similarly, to get a turtle to draw again, you use setPenDown()
    myrtle.setPenDown(true);  // starts drawing
    

Moving in Any Direction

  • You can tell a turtle to turn to an absolute heading based on the degrees of a compass
  • You tell it which direction by using the setHeading(degrees) function
  • For example:
    myrtle.setHeading(0);

3.3.7: The Turtle API

  • The turtle and its world have even more commands that you can use
  • All of these commands are part of what is called an Application Programming Interface (API)
  • Oftentimes an API is referred to as a program library, or just library
  • You can view the Turtle API pages by clicking here: Turtle API
  • These pages were created using the Doxygen documentation tool, which we will discuss later

Using the Turtle API

  • An API can tell you some things you need to know including:
    • The classes in the API
    • What the class can do (using its functions)
  • If you look through the Turtle API, you will see a description for every member function of Turtle
  • Reading the description can help you figure out how the functions work
  • The page has short descriptions at the top and longer descriptions further down the page
  • Each short description has a hyperlink to the longer description to make navigation easier
  • In the Turtle API, you can find the functions we have used so far and read what they have to say
  • Do the descriptions tell you what you need to know to use them?

About the C++ API

  • C++ also has a set of API documents that describe all its library functions
  • We will discuss the functions of the API as the course progress
  • However, if you are curious, you can browse the API at: cppreference.com

3.3.8: Summary

  • As data gets more complicated, you need a way to organize them
  • In C++, one way to organize complex data is to use a class
  • A class is a data type that a programmer defines
  • We are using classes that other programmers defined for now
  • The class we looked in this section at was called Turtle and allows us to draw using turtle graphics
  • To use the Turtle class we must include the file that contains its definition:
    #include "turtlelib.cpp"
  • In addition, we must make certain that the compiler knows the location of the file we want to include
  • We use a class by constructing objects from the class type
  • For example:
    Turtle myrtle = Turtle();
    
  • C++ has a shortcut method of constructing objects we can use as well
  • For example:
    Turtle myrtle;
    
  • Once we construct an object we can examine and manipulate it using its member functions
  • For example, the Turtle class has several member functions we can use:
    Turtle myrtle;
    myrtle.forward(3);    // move forward 3 units
    myrtle.left(45);      // turn left 45 degrees
    myrtle.right(45);     // turn right 45 degrees
    myrtle.moveTo(-7, 5); // move to coordinate -7, 5
    
  • All of the member functions we can use are described in the Turtle API

3.4: Problem Solving and Pair Programming

Learner Outcomes

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

  • Describe the steps for writing a program
  • Discuss the pros and cons of pair programming

3.4.1: Solving the Problem

  • Developing a program can require a lot of work
  • For example, we follow these steps to develop a program:
    • Analyzing and understand the problem and other specifications
    • Developing an algorithm
    • Analyzing and testing an algorithm to see if it will work
    • Translating an algorithm into source code
    • Debugging compiler errors
    • Testing the compiled program to determine if it meets requirements
    • Analyzing and debugging how your program operates
  • During this process, we run into problems we must solve
  • When developing a program it can seem like you are all alone
  • However, programming does not have to be a solo experience

Getting Help

  • Developing programs on your own is often difficult
  • You can get some help with others without cheating (see Working Together)
  • However, you have to write all the code on your own
  • A better solution than solo programming is to use pair programming

3.4.2: Pair Programming

  • Pair programming is two people working together on one computer at the same time:
    • Exactly two people: not one nor three or more
    • Exactly one computer: not two or more
  • The driver operates the keyboard and mouse
  • The navigator actively participates in the programming by:
    • Analyzing the design and code to prevent errors
    • Looking up reference materials like program syntax
  • Each person "drives" about half the time:
    • Physically get up and move positions when switching roles
  • At most 25% of your time is spent working alone:
    • Any work done alone is reviewed by the other person
  • The objective is to work together and to learn from each other
  • You cannot divide the work into two pieces with each partner working on a separate piece
  • If you are not both engaged in the process, you will not learn the material
  • More information: Pair Programming for Homework Assignments

Why Pair Program?

  • Students who pair program report:
    • Higher confidence in a program solution
    • More satisfaction with programming
  • Instructors report higher completion and passing rates

More Information

3.4.3: Best Practices

  • You may choose any other student in this class for a partner
    • You may NOT program with a person from another class
  • Both of your names appear on the assignment
  • When choosing partners and working together, certain practices help you perform better
  • Pair-programmers are more successful when they have similar experience levels
  • You should find a partner with whom you can easily exchange ideas
  • If you cannot work easily with someone, you should get another partner or work by yourself

Getting Along

More Information

3.4.4: Summary

  • Programming is about solving problems using a computer program
  • Generally, you should develop programs in two phases:
    1. Problem-solving phase: the output is a working algorithm
    2. Implementation phase: the output is a working program
  • Since defining problems, developing algorithms and implementing algorithms is hard, you can work with a partner
  • Use some care when choosing a pair-programming partner to maximize your success
  • In addition, both you and your partner should read: All I Really Need to Know about Pair Programming I Learned In Kindergarten

Check Yourself

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. Why is pair programming helpful? (3.4.1)
  2. What are the rules of pair programming? (3.4.2)
  3. Why should you change who is driving when you pair-program? (3.4.2)
  4. What is the job of the person who is not using the keyboard? (3.4.2)
  5. How do you make sure that both people learn the material when pair programming? (3.4.2)
  6. Why do the rules of pair-programming require you to use only one computer at a time to edit and compile code? (3.4.2)
  7. What is the key factor for success in using pair programming? (3.4.3)

Exercise 3.4

In this exercise we see who might be a compatible pair-programming partner for the next homework assignment.

Specifications

  1. We will count off and divide into separate groups
  2. Within your group, exchange names and email addresses, and then write down everyone's information.
  3. Next to each name, write the amount of programming knowledge and experience for that student using the following scale:
    1. Absolute beginner
    2. Some programming knowledge
    3. Can program in another programming language
    4. Can program in C++
  4. Save all the information you collect in a file named students.txt.

    Note that you can choose to have one person in your group record the information and email it to all the students in the group. However, every student must submit the same list of students.

  5. Submit the students.txt file to Blackboard as part of assignment 3.

Wrap Up

Due Next:
A2-Implementing an Algorithm (2/26/09)
A3-Drawing with Turtles (3/5/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 14 2009 @12:10:56