2: Basic Coding Skills

What We Will Cover


Continuations

Announcements

  1. Make sure you process add codes right away
  2. What to do when Canvas has problems
  3. Reminder: your last submittal to Canvas must include all your assignment files
  4. Ignore the extra -1 (or any other number) added to the end of files in Canvas
  5. Room Policies
  6. Student Behavior Policies
  7. Connecting to Hawknet Wireless Internet
  8. CodeLab Registration and Purchasing
  9. Receive emergency text alerts for things like campus closings

The Assignment Cycle

Most assignments (after the first) have three parts:

  1. Preparation:
    • Helps prepare for the problem-solving portion of the assignment
    • First make sure to complete the exercises from the prior lesson
    • Then complete several short review exercises, usually in CodeLab
    • CodeLab will tell you if you answered correctly and give hints if you make a mistake
    • If you make a mistake, try again
    • If you get stuck, get help
  2. Programming Projects:
    • Lets your explore the concepts in a more challenging way than the lesson exercises
    • We are given one or more problems for which we need to develop a solution
    • Acceptable solutions must meet a list of specifications

      specification: A condition or restriction that is insisted upon; precise requirement

  3. Tutorial:
    • Introduces the new material
    • First read the assigned reading in the textbook to understand how to solve the problems
    • Then complete the tutorial exercises as specified
    • Also, we can refer to the online lecture notes as they become available
    • If we get stuck, we can look at CodeLab answers in the Solutions tab

Homework Questions?

  • Quiz 1 (Canvas) (9/4/18)
    A1-Getting Started (9/6/18)
  • Who has installed g++? How did it go?
  • Any problems compiling the hello.cpp program?
  • Any problems with CodeLab?
  • How to read robo grading results

Questions from last class or the Reading?

  1. Computers: CPU, Memory, etc.
  2. Binary Numbers
  3. Developing a C++ Program "Hello World"
  4. Compiling and Programs

2.1: Elements of a C++ Program

Learner Outcomes

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

  • Write comments in programs
  • Include libraries and use namespaces in programs
  • Identify statements in programs
  • Code main() functions

2.1.1: Programming Languages and C++

Recall how a computer is organized:

computer diagram

Processor (CPU)

Processor (CPU)

  • The heart of a computer is the Central Processing Unit (CPU or processor)
  • A processor executes machine instructions, which are extremely primitive operations like:
    1. Move memory location 40000 into register eax
    2. Subtract the value 100
    3. If the result is positive, start processing at location 11280
  • These instructions are encoded as numbers such as:
    161 40000 45 100 127 11280
  • While the computer only understands binary, we use decimal numbers for convenience

Assemblers

  • Each processor has its own set of machine instructions
  • Looking up numeric codes for instructions like these is tedious and error prone
  • To make programming easier, computer scientists first developed a program called an assembler
  • An assembler allows a programmer to assign short names for the machine codes like:
    movw r30, r24     (copy register word - word is 4 bytes)
    subi r30, 0x12    (subtract immediate)
    breq .+8          (branch if equal)
    
  • The assembler translates the names into the correct machine codes
  • While easier for humans to use, assemblers still have two problems:
    1. We still have to enter a great many primitive instructions to create a program
    2. The instructions change from one processor to another

Higher-level Languages

  • To make programming easier, computer scientists developed higher-level languages
  • Higher-level languages like C++ and Java let us write more readable instructions like:
    if (interestRate > 100) {
        cout << "Interest rate error";
    }
    
  • Programmers call these instructions source code
  • To translate these high-level instructions to machine instructions we use a compiler

    compiler: a program that translates source code into machine instructions

  • Another advantage of higher-level languages is we can move programs to another processor more easily
  • Moving programs to another processor requires someone to write a compiler
  • After the new compiler is available, we can recompile our program with (hopefully) no changes
  • There are thousands of higher-level languages
  • The one we use in this course is C++

Early History of C++

Check Yourself

  1. True or false: computers can directly carry out C++ source code instructions.
  2. True or false: an assembler translates high-level language programs to a set of computer instructions.
  3. To translate source code to machine code we use a ________.
  4. For a high-level language like C++, which of the following statements are true?
    1. easier to program than machine code
    2. easier to program than assembler code
    3. easier for a human to read
    4. easier to move from one type of processor to another
  5. True or false: the ANSI standard for C++ was released after the ANSI standard for C.

More information

2.1.2: Example Program

  • Here is an example program like we looked at before
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    /**
        CS-11 Asn 0, helloworld.cpp
        Purpose: Prints a message to the screen.
    
        @author Ed Parrish
        @version 1.0 8/30/05
     */
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    } // end of main function
    

Brief Explanation by Line Number

  • Lines 1-7: comments -- notes to programmers
  • Line 8: adds a library (pre-written code) to our program
  • Line 9: all the standard libraries use the std namespace
  • Line 10: a blank line that we can use anywhere in our programs
  • Line 11: the main() function where all C++ programs start
  • Line 12-13: programming statements that give instructions to the computer
  • Line 14: the end of the main() function followed by another comment

2.1.3: Comments

  • Comments are ... comments -- notes to people reading the code
  • Comments are ignored by the compiler
  • Use comments to document blocks of code and to describe unusual code
  • One form of comments starts with // and lasts to end of the line
    // this is a comment
  • Another form affects a section of code: /* ... */
  • This form can span multiple lines:
    /* This is a multi-line comment
          which can be split
       over many lines or a portion of one line. */
    
    or just a portion of one line
    x = /* 41 + */ 1 ;
    

Programming Style: Block Comments

  • Block comments are the main way to document your code
  • We use block comments like the following at the start of a program file:
    /**
        CS-11 Asn 0, helloworld.cpp
        Purpose: Prints a message to the screen.
    
        @author Emma Programmer
        @version 1.0 8/20/15
     */
    
  • The grading of most programming projects includes checking the comments of our code
  • Put a comment like this at the top of the source code file for all programming projects assigned
  • On the other hand, there is usually no need to put comments in lesson exercises

Check Yourself

  1. True or false: comments are notes to the compiler.
  2. Of the following, the symbols that indicate a single line of commentary will follow is ________.
    1. /*
    2. /**
    3. //
    4. */
  3. To make C++ code more explanatory for others ________.
    1. use more English statements in a code.
    2. add comments to code
    3. avoid usage of complex calculations in code
    4. always enclose code statements in curly braces
  4. Of the following, the type of comments to use at the top of each programming project file is ________.
    1. /*...*/
    2. /**...*/
    3. //...
    4. #...
  5. True or false: comments are generally required in lesson exercises.

2.1.4: Statements and Whitespace

  • Statements are commands we give a computer in a programming language
  • A statement is similar to a sentence in English
  • Most statements end in a semicolon (;)

Example Statement: cout

  • One of the many statements of C++ is: cout << something
  • This statement is one way to send output to a console
  • For example, the statement:
    cout << "Hello, World!";
  • Sends "Hello, World!" to the console like this:
    Hello, World!
    

Preprocessor Directives

  • Some commands we place in our source code start with a # sign
    #include <iostream>
    
  • Technically, this command is known as a preprocessor directive
  • A preprocessor directive is a command to the compiler rather than a command in the program
  • Find a statement and preprocessor directive in the code below
#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!\n";
    return 0;
}

Whitespace

  • Whitespace: blank lines, spaces, and tabs
  • The compiler ignores extra white space
  • This lets us add extra whitespace to our code, making it easier to read

Programming Style: Line Length

  • Do not make your lines longer than 80 characters so code is easier to read
  • Longer lines can cause problems in many terminal windows, text editors and other programming tools

Check Yourself

  1. Statements usually end in a ________.
  2. To make the code easier to read, always limit line lengths to ________ characters.
  3. True or false: the compiler ignores extra whitespace.

2.1.5: The main() Function and Blocks

  • C++ programs are structured into subprograms called functions

    Function - a named block of code that executes a series of statements to perform a task

  • Every C++ program has at least one function, main, defined like this:
    int main() {
        // program statements go here
    }
    
  • Programs begin executing at the first line of the main() function
  • The int means main returns a value of type int (more on this later)
  • For now, mimic the first line of main

Sequence

  • Within a function, code runs from top to bottom in a continuous sequence
  • Example code sequence:
    cout << "Hello World!\n";
    cout << "Goodbye World!\n";
    return 0;
    
  • For a program to run correctly, we must place statements in the correct order

Blocks

  • A block is a section of code grouped together
  • C++ is known as a block-structured language
  • This means that most source code is grouped within pairs of matching { }
  • Left brace { begins the body of every function
  • Right brace } ends the body of every function
  • All functions have associated blocks
  • However, as we will see later in the course, we can group statements into blocks in other places as well

Programming Style: Indentation Inside Braces

  • Always indent statements inside braces to make code easier to read
  • After an opening curly brace "{", start indenting
  • After a closing brace "}", remove the level of indentation as shown below
#include <iostream>
using namespace std;

int main() { // start indenting after opening {
    cout << "Hello, World!\n";
    return 0;
} // stop indenting after closing }

Check Yourself

  1. True or false: every C++ program has at least one function.
  2. A C++ function is ________
    1. A mapping of a domain value to a codomain value
    2. A named block of code that executes a series of statements
    3. A named block of code that returns a value for a given argument
    4. Any procedure that returns a value
  3. True or false: every C++ program has a main() function.
  4. Every C++ program starts executing ________.
    1. at the top of the file
    2. at the start of the main function
    3. immediately after the program compiles
    4. when the program is finished
  5. True or false: the default behavior for program statements within a function is to execute sequentially.
  6. A block is a section of ________ grouped together with curly braces.
  7. True or false: always indent within curly braces.

2.1.6: Using Libraries and Namespaces

  • In programming terms, a library is a collection of prewritten code we can use in our programs
  • This saves us the effort of writing our own code for commonly-used functions
  • C++ has a number of standard libraries
  • These libraries place their code in what is called the std namespace

Libraries and include Directives

  • To use a library, we add the include preprocessor directive to our programs
    #include <libraryName>
  • Most of our programs begin with a declaration like:
    #include <iostream>
  • The iostream library is for console input and output (I/O)
  • This library allows us to use the word cout for sending data to a terminal screen
  • Other libraries exist for math, strings and more (cover later)
  • Some compilers are picky about spaces in include directives
    • Do not put spaces before or after the # sign
    • Do not put spaces inside the angle brackets

Namespaces

  • Namespace: a set of name definitions where all the names are unique
  • As an example, when we use the word cout we expect the command to send data to a terminal screen
  • However, someone may write a cout command that does something different
  • We keep them separate by prepending the namespace
    std::cout << "Hello World!\n";
    
  • Above we prepend std, which is the standard namespace for standard libraries
  • For complex programs, most programmers prefer prepending namespaces to clarify the code
  • To keep things simple in the beginning of the course, we add the directive:
    using namespace std;
  • Thus, most of our programs will begin with two statements:
    #include <iostream>
    using namespace std;
    
  • When we add more namespaces later in the course, we will start prepending the namespace

Check Yourself

  1. A library is a collection of ________ code.
  2. We use libraries in our programs to ________.
  3. We tell the compiler to use the library named iostream by writing ________.
  4. To tell the compiler to use the standard namespace by default write ________.

Exercise 2.1: Elementary C++

In this exercise we examine the basic elements of a C++ program.

Specifications Part A: Experimentation (5m)

  1. Start your text editor and enter the following code:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    /**
        CS-11 Asn 0, helloworld.cpp
        Purpose: Prints a message to the screen.
    
        @author Ed Parrish
        @version 1.0 8/30/05
     */
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    } // end of main function
    
  2. Save the file as "hellome.cpp".
  3. Compile the code using:
    g++ -Wall -Wextra -Wpedantic -o hellome hellome.cpp
    

    If you have problems, ask a classmate or the instructor for help as needed.

  4. Run the code and verify you get the message, "Hello, World!"
    $ ./hellome
    Hello, World!
    
  5. Try changing the message to personally greet you with your own name, like the following:
    Hello, Ed Parrish!
    
  6. The code that starts with /** and ends with */ is known as a block comment. Comments are parts of code that are ignored by the compiler. Delete the entire block comment and then recompile and rerun your code.

    You should see no change in how your code compiles or runs. If you see a difference, ask a classmate or the instructor for help as needed.

  7. Look at the following line of the code:
    } // end of main function
    The last part of the line is another type of comment that starts with // and lasts until the end of the line. Delete the comment and then recompile and rerun your code.

    You should see no change in how your code compiles or runs. If you see a difference, ask a classmate or the instructor for help as needed.

  8. Remove the directive using namespace std; and then try to recompile the code.

    Your program should not compile and you should get an error message. If you have a different experience, ask a classmate or the instructor for help as needed.

  9. Restore the directive using namespace std; back into your program and verify that it compiles.

    If you have problems, ask a classmate or the instructor for help as needed.

When finished, move on to Part B.

Specifications Part B: Reflection (3m)

  1. Create a second text file named "syntax.txt" and record your answers to the following questions:
    1. Does a comment change the way that a program compiles or runs?
    2. What error message does the compiler report when you leave out the following command?
      using namespace std;
  2. Submit both your hellome.cpp and syntax.txt files to Canvas as part of assignment 2.

When finished, please help those around you.

2.1.7: Summary

  • C++ has two styles of comments:
    • //
    • /* ... */
  • Comments help document what a program does:
    • Use block comments at beginning of a file and before functions
    • Otherwise, use comments them sparingly
  • Statements are the commands we give a computer in a program
  • C++ has standard libraries of prewritten code
  • Definitions for these libraries are collected in a namespace called: std
  • Thus, most of our programs will begin with two declarations:
    #include <iostream>
    using namespace std;
    
  • Every C++ application starts with a function named main()

Self Reflection

Answer these questions to check your understanding. If you are not sure, then follow the links to the section and review the material.

  1. What is the purpose of a comment? (2.1.3)
  2. What styles of comments are allowed in C++? (2.1.3)
  3. What is a statement? (2.1.4)
  4. How can you tell which lines of a program are statements? (2.1.4)
  5. What statement do you use to print a message to the console window? (2.1.4)
  6. What is meant by the term "whitespace"? (2.1.4)
  7. Where does every C++ program start? (2.1.5)
  8. What code do you write for the main() function? (2.1.5)
  9. What are the rules for indenting code? (2.1.5)
  10. How do you include libraries in your C++ programs? (2.1.6)

2.2: Memory Concepts

Learner Outcomes

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

  • Describe why data is important in a computer program
  • Write code for declaring variables and assigning them values
  • Create variable names according to the rules of C++
  • Identify the literal values of basic data types
  • Write code to get input from a user and display the value of variables

Image
Image source: Digital Psychology

2.2.1: Importance of Memory

  • Let us pretend that we have a friend, named Grace, and we want to remember her phone number: 555-2368
  • We can store our friend's phone number in our memory
  • We even label our friend's phone number, like "Grace's phone number"
  • We do not really know where in our brain we store Grace's phone number
  • However, whenever we need her phone number, we say to our self, "What is Grace's phone number" and out pops 555-2368
  • Just like we store our friend's number in our memory, we can store it in a computer's memory
  • We store data in a computer program using a variable

    variable: the name of a place to store data in a computer's memory

  • Just like we do not know where in our brain we store a phone number, we do not know where in computer memory we store data
  • We simply give it a name and let the compiler decide where to store the data

Why Data Matters

  • Why should we care about variables or storing data?
  • Variables are the most important part of any computer program
  • Just like in real life, it is hard to do anything without memory
  • Consider a simple algorithm like adding two numbers:
    1. Get the first number
    2. Get the second number
    3. Add the first and second number and assign it to sum
    4. Display that sum is the result
  • How many variables did we need for this algorithm?
  • To find out, let us do some role playing
  • Imagine a conversation between Hal and Grace:
Hal: Hey Grace, I just learned to add two numbers together.
Grace: w00t!
Hal: Give me the first number.
Grace: 2
Hal: OK, give me the second number.
Grace: 3
Hal: OK, the answer for 2 + 3 is 5
  • After Grace says, "2", Hal has to store the number in his memory
  • The same things happens with the number, "3"
  • Even if the numbers were given in the same sentence, Hal would have to store the numbers somewhere in his memory
  • After adding the two numbers together, Hal has to store the result of the addition, at least temporarily, so he can state the answer
  • If we were to write a program to add two numbers together, the computer would have to use memory just like Hal

Check Yourself

  1. The name of a location to store data in a computer's memory is known as a(n) ________.
  2. True or false: remembering data is rarely important when processing information.
  3. To add two numbers, we need to store at least ________ pieces of information.
    1. 0
    2. 1
    3. 2
    4. 3

Memory organized by bytes

2.2.2: Introduction to Variables

  • Recall how a computer is organized
  • Main memory is organized as a long list of memory locations
  • Each location stores one byte and is identified by an address number
  • 1 gigabyte (GB) is about 1 billion bytes
    In RAM memory terms, 1 GB is 230, 10243 or 1,073,741,824 bytes

Storing Data

  • A key part of a computer is memory
  • To store and retrieve data in a program we use a variable
  • A variable is a name for a location in a computer's memory

Variables are a location in the computers memory

Variable Declaration

  • Here is an example C++ variable declaration:
    int num1;
    
  • When we declare a variable we tell the computer to set aside space to store data in its memory
  • Notice that a variable declaration has two parts:
    • int: the type of data the variable will store, integer values in this case
    • num1: the name of the variable, which we make up while coding
  • Variable names are a sequence of letters, numbers and the underscore ( _ )
  • However, variable names cannot start with a number and cannot contain spaces

Data Types

  • Like human memory, a computer must encode information before storage
  • As programmers we tell the computer how to encode information using data types
  • A commonly used numerical data type is int, which is shorthand for integer
    int num1;
    
  • An int specifies a whole number with no fractions or decimal points
  • If we want to store numbers with a decimal point, we use a floating point type like double
    double pi;
    

Some Commonly Used Numerical Data Types

Type Bytes Use
int 4 integers (whole numbers) like -1, 0 and 123
double 8 double-precision floating-point numbers like -1.23 and 3.14159

Assignment

  • After we declare a variable, we may store a value in the variable
  • One way to store values is with an assignment operator, which is the "equals sign" (=)
  • We assign a value to the variable with an assignment statement in this form:
    variable = expression;
  • Where:
    • variable: the name of the variables
    • expression: the data to store in the variable
  • An assignment statement stores the value of expression (right side) in the variable (left side)
    • Switching sides is a common error
  • An expression is a group of operators, numbers and variables that compute a value
  • An assignment statement is like a simple equation where an expression is assigned to a variable
  • Examples:
    int num1;       // variable declaration
    num1 = 45;      // assignment
    int num2 = 12;  // declaration + assignment
    int total = num1 + num2;  // more complex expression
    
  • Notice that we can combine variable declaration with assignment
  • A common error is to forget to assign a value to a variable!!
  • Avoid this error by assigning a value whenever declaring a variable

Variables by Analogy

Empty box labeled a

  • Variables are like boxes made of computer memory (images source: David Goodger)
  • A computer memory location can hold one value at a time, thus our box can hold only one value
  • We put names on boxes to tell one box from another, like "a":
  • This is like declaring the variable "a"
    int a;
    
  • When we first declare a variable the box is empty but has a name
  • Storing values in a variable is like putting values in a box

    value 1 in box a

  • For example, we assign the variable "a" the value 1
    a = 1;
    
  • We put names on a box
  • We put values inside of boxes
  • When we want to see the value inside a box we look at it with code like:
    cout << a << "\n";
    
  • If we change the value of a variable, we are putting a new value in the same box, like:

    value 2 in box a

    a = 2;
    
  • Making a new variable and assigning one variable to another makes a copy of the value and puts it into the new box:
    int b = a;
    

    value 2 in box bvalue 2 in box a

  • We now have two different boxes that have independent values

Activity: Code Variables (3m)

  1. Start your text editor and open the hellome.cpp from the last exercise.
  2. Inside the curly braces of main(), declare an integer variable named "favNum" and assign it the value of your favorite number, like:
    int favNum = 42;
    
  3. After displaying your name, print the value of your favorite number like:
    cout << "Your favorite number is " << favNum << ".\n";
    
  4. Compile and run the code and verify your program shows output like the following:
    Hello, Ed Parrish!
    Your favorite number is 42.
    

When finished, please help those around you. Help is available during break or after class if you cannot finish in the allotted time.

Check Yourself

  1. The name of a location to store data in a computer's memory is known as a(n) ________.
  2. To specify the type of data stored in a variable, variable declarations include a(n) ________ ________.
  3. True or false: the "equals sign" (=) is the assignment operator in C++.
  4. The following code prints the value ________.
    int x = 42;
    cout << x << "\n";
    
  5. After executing the following statement, the value of number is ________.
    int number;

computer diagram

2.2.3: Input and Output

  • Recall the main parts of a computer
  • Input sends information to the computer
  • Output is the computer sending information
  • We now look at how to code input and output

Output

  • We have been using cout to display information on our video monitors
  • The command cout sends data to standard output, usually the terminal (console) window
  • The "<<" takes data from the right-hand side and sends it to the console
    cout << "Hello, World!" << endl;
    
  • The endl prints a newline so the next item displayed goes on a new line.
  • Notice the last letter of endl is an "el"--not a one!
  • Most basic data can be output to the console including
    • Variables (like num1)
    • Literals (like 12.34)
    • Expressions (like num1 + 12.34)
  • We can display multiple values in one cout
  • However, each data item must be separated with a << operator
  • For example:
    int numberOfDragons = 3;
    cout << numberOfDragons << " dragons.\n";
    
  • Three values are output in order from left to right:
    1. The value of the variable numberOfDragons
    2. A literal string " dragons."
    3. An end-of-line (newline) character
  • Prints out: 3 dragons.
  • Notice that "\n" may be used instead of endl to print a newline

User Input

  • So far we have used an assignment operator "=" to assign a value to a variable
    int numberOfDragons = 3;
    
  • Another way to assign a value to a variable is to read it from the console
  • The keyboard input console is called cin (console input)
  • We use the >> operator with cin to send data to a variable
  • For example:
    cin >> numberOfDragons;
  • In this example, whatever valid integer number the user types is stored in the variable numberOfDragons

Prompting Users

  • Good programming practice is to always "prompt" users for input like:
    cout << "Enter number of dragons: ";
    int numberOfDragons;
    cin >> numberOfDragons;
    cout << "You entered " << numberOfDragons
         << " dragons\n";
    
  • Note that we do not put a newline after the prompt
  • The prompt waits on the same line for keyboard input like:
    Enter number of dragons: _
    
  • Where the underbar above denotes where keyboard entry is made
  • Every cin should have a cout prompt before it so users know what to enter

Check Yourself

  1. The following code outputs ________.
    int numberOfGames = 12;
    cout << numberOfGames << " games played.\n";
    
  2. Before getting input from a user, common practice is to display a(n) ________.
  3. Of the following statements, the one that places input into the variable "value" is ________.
    1. value >> cin;
    2. cin >> value;
    3. value << cin;
    4. cin << value;
  4. True or false: the << and >> always point in the direction the data is flowing.

Exercise 2.2: Adding Two Numbers (8m)

In this exercise we will write a program to add two numbers together. When it runs, the program acts like this:

Enter the first number: 2
Enter the second number: 3
The sum of 2 and 3 is 5.

Make sure to compile after each step so you know where an error is located if you make a mistake.

Specifications

  1. Copy the following program into a text editor, save it as variables.cpp, and then compile and run the starter program to make sure you copied it correctly.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Input first variable
    
        // Input second variable
    
        // Calculate sum
    
        return 0;
    }
    
  2. In main(), declare an int variable named num1 and assign it a value of 0:
    int num1 = 0;

    For more information on declaring variables, see section: 2.2.2: Introduction to Variables

  3. Add code to display a prompt to the screen:
    cout << "Enter the first number: ";

    For more information on prompting users, see section: 2.2.5: Input and Output

  4. Add a statement to input a new value for the variable and store it in memory:
    cin >> num1;

    For more information on reading data from users, see section: 2.2.5: Input and Output

  5. Declare a second variable of type double named num2 and assign it a value of 0.0:
    double num2 = 0.0;

    For more information on data types, including the double data types, see section: 2.2.4: More About Data Types

  6. Add code to display a prompt to the screen:
    cout << "Enter the second number: ";
  7. Add a statement to input a new value for the variable and store it in memory:
    cin >> num2;
  8. Declare a third variable of type double named total and assign it the result of adding the two variable together:
    double total = num1 + num2;
  9. Write another statement that displays the result of adding the two numbers together:
    cout << "The sum of " << num1 << " and "
         << num2 << " is " << total << ".\n";
    
  10. Compile and run your program to make sure it works correctly.
  11. Submit your program source code to Canvas as part of assignment 2.

When finished, please help those around you.

Completed Program

When finished, check your source code by clicking here. Click to show answer

Reviewing another solution after you have completed your own is often helpful in learning how to improve your programming skills.

2.2.4: Summary

  • Variables are how we can store data in our programs
  • Variables must be declared before use like:
    int x;
    
  • Notice that the variable declaration has two parts:
    • int: the type of data the variable will store, integer values in this case
    • x: the name of the variable, which we make up while coding
  • Once declared, we assign a value to the variable like:
    x = 42;
    
  • Simple assignment statements have a variable, equals sign and an expression:
    variable = expression;

User Input

  • Another way to store data in a variable is to read it from the console
  • cin is an input stream bringing data from the keyboard
  • The ">>" point towards where the data goes
  • When designing I/O:
    • Prompt the user for input
    • Echo the input by displaying what was input
  • cout is an output stream sending data to the monitor
  • The insertion operator "<<" inserts data into cout
  • There are two ways to output a newline character:
    cout << "Hello World!\n";
    cout << "Hello World!" << endl;
    

Self Reflection

Answer these questions to check your understanding. If you are not sure, then follow the links to the section and review the material.

  1. Why do you need to store data when creating a program? (2.2.1)
  2. How do you store information in a computer's main memory? (2.2.2)
  3. What code would you write to declare an int variable named foo and assign it a value of 10? (2.2.2)
  4. What code would you write to display a variable named foo to standard output? (2.2.3)
  5. What code would you write to input data from the keyboard and store it in a variable named foo? (2.2.3)
  6. Why is it a good practice to prompt users before input? (2.2.3)
  7. What are two ways to assign a value to a variable? (2.2.3)

2.3: 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

2.3.1: Computations 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 a pocket to get the total value in dollars
  • If we know the number of each coin type what would be the formula to calculate the dollar value?
    int pennies = 8;
    int nickels = 5;
    int dimes = 4;
    int quarters = 3;
    
  • To implement this formula, we will need to use numbers and arithmetic
  • Remember that C++ has two general types of numbers: integers and floating-point

Integers

  • An integer number is zero or any positive or negative number without a decimal point
  • Examples of integers include:
    0   1   -1    +5    -27   1000    -128
    
  • We call plain numbers like these literal integers because they stand for what they look like
  • By comparison, a variable may contain an integer value but is not a literal integer
    int num1 = 3;
    
  • Literal numbers are constant and do not change while a program executes
  • The compiler usually stores integers in four (4) bytes of computer memory

Floating-Point Value

  • A floating-point number is any signed or unsigned number with a decimal point
  • A floating point number approximates a real number and has a trade-off between range and precision
  • 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 compiler usually stores floating-point numbers in eight (8) bytes of computer memory

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;
}

Check Yourself

  1. The two types of numbers in C++ are ________ and ________.
  2. Of the following literal numbers, the single integer is ________.
    1. 1
    2. 1.2
    3. 1.23
    4. 1.234
  3. For the following code, the literal number is ________.
    int pennies = 8;
    

2.3.2: Arithmetic

  • C++ uses the following operators for arithmetic:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder after integer division)
  • Modulus is a type of division operation for integer numbers
  • The first four operators should be familiar and we will discuss modulus (%) today

Precedence Rules

  • Precedence: what gets done first
  • Arithmetic operators are processed in algebraic order:
    1. Parenthesis: ( )
    2. Unary operators: +, -
    3. Multiplication, division, modulus: *, /, %
    4. Addition, subtraction: +, -
  • Binary operators of same precedence are evaluated from left to right
  • As in algebra, multiplication and division (including modulus) are performed before addition and subtraction
  • To change the order of operation, we use parentheses
  • For example:

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

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

  • Notice that we cannot use parenthesis to indicate multiplication, but must explicitly use the '*' operator in C++

Examples of Expressions

Algebra Expression C++ Expression
2(10 + 5) 2 * (10 + 5)
1

12.2 + 3 · 7.3
1 / (12.2 + 3 * 7.3)
10 - 7

3.2 + 9 · 1.6
(10 - 7) / (3.3 + 9 * 1.6)
2 · 42 2 * 4 * 4

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 )

Check Yourself

  1. The five arithmetic operators in C++ are ________.
    1. +, -, /, *, %
    2. +, -, \, *, %
    3. +, -, /, *, ^
    4. +, -, \, *, ^
  2. The first operation performed in the following arithmetic expression is ________.
    1 + 2 * 3 / 4 % 5
    
  3. If we wanted a different ordering of operations in the above example, we add ________ to the expression.

2.3.3: Mixed-Mode Expressions

  • Recall that different data types are stored in different forms
    • An integer (int) is usually stored in 4 bytes
    • A floating-point number (double) is usually stored in 8 bytes
    • The format of the types 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 an 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

Check Yourself

  1. The result of adding an integer with a double in the following expression is ________.
    1 + 2.4
  2. In the above expression, C++ converts the integer 1 to type ________.
  3. The data type of the number returned by the following expression is ________.
    3 + 4.5

Exercise 2.3a: Calculator Basic (7m)

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

Specifications

  1. Type the following program into a text editor, save it as arithmetic.cpp, and then compile and run the starter program to make sure you typed it correctly.

    Starting code

  2. Within the curly braces of the main() function, declare two double variables named a and b, and assign them a value of 5 and 2 respectively. For instance:
    double a = 5, 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;
    

    Notice that the last letter on endl is a lower-case "L", NOT a one. The output when you run the program should look like this:

    a + b = 7
    

    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 = 7
    a - b = 3
    a * b = 10
    a / b = 2.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 = 7
    a - b = 3
    a * b = 10
    a / b = 2.5
    a + b / 2 = 6
    (a + b) / 2 = 3.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: 2.3.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 explore in the next section:

    • Truncation in integer division
    • Modulus (%) operator
  7. Save your arithmetic.cpp file as we will add to it in the following sections.

When completed, please help those around you.

Discussion Questions

  1. What is wrong with the following code?
    cout << "a + b = a + b" << endl;
    
  2. How should the above code be written?

2.3.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.5
    7 / 2.0     // 3.5
    7.0 / 2     // 3.5
    
  • 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, we 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
  • The modulus operator (%) can only be used with integer type operands and has an integer type result
  • C++ allows a negative modulus result from a modulo operation

Uses of Modulus and Division

  • We can use modular arithmetic for operations that roll over like clock arithmetic
  • For example, if the time is 9:00 now, in 4 hours it is 1:00
    int hours = 9;
    hours = (9 + 4) % 12;
    cout << hours << endl;
    

    clock faces

  • We can extend the same idea to work with weeks, minutes and seconds
  • Modulus is also useful when working with different units like yards, feet and inches
  • For example, 49 inches is 1 yard, 1 foot and 1 inch which is calculated like:
    int lengthInches = 49;
    int yards = lengthInches / 36;
    int remainder = lengthInches % 36;
    int feet = remainder / 12;
    int inches = lengthInches % 12;
    cout << yards << " yards, "
         << feet << " feet and "
         << inches << " inches\n";
    
  • Another use of the modulus operator is to split the last digit off of an int
    int num = 123;
    int lastDigit = num % 10;
    cout lastDigit << endl;
    
  • We can get the first digit using integer division
    int firstDigit = num / 100;
    
  • The middle digit(s) need a combination of integer division and modulus
    int secondDigit = num / 10 % 10;
    

Program using Division and Modulus to "Split" Digits

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

int main( ) {
    int num = 123;
    int lastDigit = num % 10;
    int secondDigit = num / 10 % 10;
    int firstDigit = num / 100;
    cout << num << ": " << lastDigit << " " << secondDigit
         << " " << firstDigit << endl;

    return 0;
}
  • We can use modulus and integer division to translate integers to different bases as well
  • For example, to convert from decimal to binary we divide by 2 and take the remainder of 2 instead of 10

Program Changing Decimal to Binary

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

int main() {
    int decimalNum = 6, newNum = 0; //what is 6 in binary?
    int firstBit = 0, secondBit = 0, thirdBit = 0;
    firstBit = decimalNum % 2; //rightmost bit
    newNum = decimalNum / 2;
    secondBit = newNum % 2;
    newNum = newNum / 2;
    thirdBit = newNum % 2;
    cout << decimalNum << " in binary is "
         << thirdBit << secondBit << firstBit << endl;
    return 0;
}

Check Yourself

  1. In division between two integer numbers, the remainder is ________.
    1. rounded up
    2. rounded off
    3. averaged
    4. truncated
  2. Of the following, the expression that returns an integer value is ________.
    1. 22.0 / 7
    2. 22 / 7.0
    3. 22.0 / 7.0
    4. 22 / 7
  3. To compute the integer remainder we use the operator ________ .
  4. What is the result of the following arithmetic operations?
    1. 9 / 4   (answer)
    2. 17 / 3 (answer)
    3. 14 / 2 (answer)
    4. 9 % 4   (answer)
    5. 17 % 3 (answer)
    6. 14 % 2 (answer)

Exercise Continued: Using Integer Division (3m)

In this part of the exercise we use integer division and modulus.

  1. Integer Division: Modify your arithmetic.cpp code from the last Exercise by changing the data type of the two variables from double to int, like this:
    int a = 5, b = 2;
    
  2. 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). We have to watch out for this in C++ programming or we may get unexpected results in our calculations.

  3. 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;
    cout << "a / b % b = " << a / b % b << endl;
    cout << "a / (b * b) = " << a / (b * b) << endl;
    
  4. Compile and run your program again with this added statement. Your program should now display the following output:
    a + b = 7
    a - b = 3
    a * b = 10
    a / b = 2
    a + b / 2 = 6
    (a + b) / 2 = 3
    a % b = 1
    a / b % b = 0
    a / (b * b) = 1
    
  5. Save your arithmetic.cpp file as we will add to it in the following sections.

When completed, be prepared to answer the following questions and then help those around you.

Discussion Questions

  1. What happens to a remainder in integer division?
  2. What is one use for the modulus operator?
  3. The last three operations produced the binary number 101. What is the decimal equivalent?

Image
Source: Wikipedia

2.3.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 returns or produces a value ("output")
  • To make use of mathematical functions we need to store or display the returned 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
    #include <cmath>
    
  • Some of the functions are listed below
  • Note that the pow() function needs a floating-point type like double as the first argument

Some Commonly Used Math Functions

Name Description Example Result
abs absolute value abs(-3.9)
abs(3.9)
3.9
3.9
exp exponent of e (ex) exp(1.0) 2.71828
pow powers (xy) pow(2.0, 3) 8
sqrt square root sqrt(4.0) 2
sin sine sin(0.0) 0
cos cosine cos(0.0) 1

Some Commonly Used Nearest Integer Functions

Name Description Example Result
ceil ceiling: round up ceil(3.456)
ceil(3.543)
4
4
floor floor: round down floor(3.456)
floor(3.543)
3
3
round rounding: round off round(3.456)
round(3.543)
3
4
  • Nearest Integer Functions return floating point numbers that are the closest to an integer value

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);
    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

Check Yourself

  1. C++ mathematical functions take an ________ and return a value.
  2. The name of the library that contains many common mathematical functions is ________
  3. Enter an expression to calculate the square root of the number 49.

    answer

  4. To round up a number, call the mathematical function ________.
  5. Use a ________ to save the value returned from a mathematical function.

Exercise 2.3b: Calculator Deluxe (3m)

In this part of the exercise we use mathematical functions to create a deluxe calculator.

Specifications

  1. Start with your arithmetic.cpp code from the last Exercise.

    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.

  2. Add the following statement to your program:
    cout << "sqrt(a + b) = " << sqrt(a + b) << endl;
    
  3. 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;
    
  4. Compile and run your program again with this added statement. Your program should now compile and display the following output when run:
    a + b = 7
    a - b = 3
    a * b = 10
    a / b = 2
    a + b / 2 = 6
    (a + b) / 2 = 3
    a % b = 1
    a / b % b = 0
    a / (b * b) = 1
    sqrt(a + b) = 2.64575
    
  5. Save your program source code that displays all ten (10) calculator operations so you can submit it to Canvas as part of assignment 2.

When completed, please help those around you. Then compare your code to the example below. Your code need not be exactly the same but it is helpful to see other solutions after you have solved the problem yourself.

Completed Program

Listing of arithmetic.cpp

Discussion Questions

  1. How natural does arithmetic seem in C++ compared to what you normally use?
  2. A mathematical function has an input and an output. What is the input and output of the C++ sqrt() function?
  3. What is the value of 2.64575 squared?

2.3.6: Summary

  • 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, like:
    double area = 0.0, radius = 4.3;
    area = 2.44159 * radius * radius;
    
  • As in algebra, multiplication and division are performed before addition and subtraction
  • To change the order of operation, we use parenthesis
  • Recall that the results of integer division are truncated
    7 / 2       // 3
  • We must use modulus operator (%) to get the remainder value
    7 % 2       // 1 (remainder)
  • For more complex operations we use mathematical functions from libraries such as cmath
    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, we use parenthesis to change the order of operations

Self Reflection

Answer these questions to check your understanding. If you are not sure, then follow the links to the section and review the material.

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

2.4: Developing Computer Programs

Learner Outcomes

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

  • Describe various kinds of programming errors
  • Find the syntax errors in programs

2.4.1: Solving Problems with Code

  • Creating programs is like solving puzzles: they take some work to figure out
  • In this lesson we discuss a general approach to solving problems with computer programs

Computer parts: input, storage, processor, output
Image source: code.org

Parts of a Computer Program

  • Remember that all computers have four parts
    1. Input
    2. Processing
    3. Storage
    4. Output
  • Similarly, a computer program has four parts
    1. Input data
    2. Process data
    3. Store data
    4. Output information
  • Each part may be repeated many times
  • Most programs we write have all these parts

Four Steps to Solving a Problem

  • A computer program is an algorithm implemented in computer code

    Algorithm: A sequence of precise instructions leading to a solution

  • To write a program we must develop a computer algorithm
  • Our approach is based on Polya's Four Step Problem Solving Process and has four parts
    1. Understand the problem
    2. Create a plan and check it
    3. Translate to code and perfect the plan
    4. Test and debug the code
  • The end results is a computer program that solves a problem

Check Yourself

  1. A sequence of precise instructions to accomplish a task is called a(n) ________.
  2. Most all computer programs include steps to ________.
    1. input data
    2. store data
    3. process data
    4. output information
    5. do all of these
  3. The first step to solve a problem with a computer program is to ________.
    1. create a plan and check it
    2. test and debug the code
    3. translate to code and perfect the plan
    4. understand the problem

2.4.2: Understanding the Problem

  • The first step in solving a problem is to understand it
  • This section suggests ways to analyze and understand a problem

Starting Out

  • When analyzing a problem, start by reading the directions
  • After you read the directions, ask yourself, "what is the goal of the problem?"
  • Also ask, "what are the inputs and outputs?"
  • Then try restating the problem in your own words
  • If you were given code to start with ask yourself
    1. What does it do?
    2. Why do you think it's there?

Ask Questions

  • As we analyze a problem, we naturally ask questions like: What? When? Why? Where? How?
  • Here are some questions that are often useful to ask when faced with a programming problem:
    1. What are you asked to find or output?
    2. Can you restate the problem in your own words?
    3. Is this problem similar to something covered in the lesson?
    4. Can you think of a picture or a diagram that might help you understand the problem?
    5. What input is needed or provided?
    6. What calculation must be performed?
    7. What data is needed for the calculations?
  • Start by reviewing this list and answering the questions that seem pertinent to the problem
  • Ask more questions as the analysis continues until you have a solution

Activity: Understanding the Problem (2m)

  1. To help us understand the development process we have an example problem

    Write a program that greets the user with a message and asks for a number as a percentage. The program then displays the percentage as a floating-point (double) number.

  2. The input and output of the program looks like:
    Hello out there!
    Enter a number as a percent: 10
    As a double the number is: 0.1
    

    In the above example run, the users entered the value shown in aqua italics (for emphasis) to produce the output. Your program does NOT print the characters in aqua italics, nor does the user input appear in aqua italics.

  3. As a first step, spend two minutes to open a text editor and rewrite the problem in your own words.
  4. Save the text of your example problem rewrite in a file named "plan.txt".
  5. Be prepared to share your problem rewrite with the class.

Check Yourself

  1. The first step to understand a problem, as assigned in this course, is to ________.
    1. restate the problem in your own words
    2. identify the inputs and outputs
    3. determine if starter code was provided
    4. read the directions
  2. The first step in problem solving is ________.
    1. To write the expression that calculates the answer
    2. To understand the problem and its inputs and outputs
    3. To do examples by hand that confirm the solution will work
    4. To write C++ code that can be executed and tested
  3. Useful questions to ask while trying to understand a problem include ________.
    1. What are you asked to find or output?
    2. Is this problem similar to something covered in the lesson?
    3. What input is needed?
    4. all of these
  4. The reason to restate the problem in your own words is because ________.
    1. to correct grammar errors in the problem statement
    2. the original words may not be an optimal statement of the problem
    3. restating the problem in your own words guarantees that the code will be correct in most cases
    4. if you cannot restate a problem, it is unlikely you will be able to write code to solve it

2.4.3: Creating a Plan

  • Our goal for the plan is to design an algorithm for a computer
  • An example algorithm:
    Computer algorithm to square any number:
    1. output "Enter a number"
    2. input number
    3. x = number * number
    4. output "The square of the number is "
    5. output x
    
  • Notice that the steps are combinations of input, processing (calculation), storage, and output
  • There are many reasonable ways to solve problems and generate algorithms
  • The following is a partial list of strategies

Problem Solving Strategies

  • Make an orderly list of steps
  • Draw a diagram or picture
  • Look for a pattern
  • Use a formula
  • Compare to a previously solved problem
  • Eliminate possibilities
  • Work backwards (output, processing and storage, input)
  • Break into smaller pieces and solve one small part at a time
  • Solve an equivalent problem
  • Guess and check

Writing and Checking the Plan

  • Once we have a plan we write down the steps
  • Write each step on its own line like the example algorithm above
  • Make sure the plan has steps for:
    1. input
    2. storage
    3. processing
    4. output
  • Check the plan by working out an example
    Computer algorithm to square any number:
    1. output "Enter a number"
    2. input number (example: 10)
    3. x = number * number (10 x 10 is 100)
    4. output "The square of the number is "
    5. output x (x is 100)
    
  • If you do not get the correct result then revise the algorithm

More Information

Activity: Devise a Plan (5m)

  1. In the same file as the previous activity, prepare a plan and list the steps needed to solve the problem.
  2. To test your plan, work out an example.
  3. Be prepared to share your plan.
  4. Save your plan.txt file to turn in with the other lesson exercises for the week.

Check Yourself

  1. Of the following, a computer cannot directly ________.
    1. input data
    2. store data
    3. output information
    4. devise a plan
  2. The goal of the planning phase is a(n) ________.
  3. True or false: a computer can perform any algorithm step we can write down.
  4. The reason to check your algorithm "by hand" is because ________.
    1. C++ code is not able to capture the subtleties of complex problems
    2. it is faster to do computations by hand than to do them by computer
    3. checking a problem "by hand" guarantees that programs will be correct
    4. if you cannot compute a solution by hand, it is unlikely you will be able to write a program that can do it

2.4.4: Translating to Code

  • In this section we look at translating to code and perfecting the plan
  • When writing software, always start with something that compiles and runs
  • As an example, start with the following code that compiles and runs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
    CS-11 Asn 0, program.cpp
    Purpose: Your problem restatement here.

    @author Your name
    @version 1.0 Today's date
 */
#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!\n";
    return 0;
}

Activity: Translating to Code (5m)

  1. Start a new file, copy the above starter code into the file, and save the file as double.cpp.
  2. Compile to make sure you are starting out right.
  3. Fill in the following information in the comment block
    1. program name
    2. your problem restatement
    3. your name
    4. today's date
  4. Now copy your algorithm steps from your plan (from the last activity) into main() between the curly braces { }.
  5. Before each step of the algorithm, add two slashes (//) to make each line a comment.

    For example if one line of your algorithm was:

    output "Hello out there."
    
    You would add inside C++
    // output "Hello out there."
    
  6. After copying and commenting all the algorithm steps, compile to make sure the code has no setup errors.

    Ask for help, if needed, to find setup errors.

  7. After each commented algorithm step, add the C++ statements needed to implement the algorithm step.
    // output "Hello out there."
    cout << "Hello out there." << endl;
    
  8. Compile after adding each statement (or so) of code.

    If the code does not compile then you know where the problem exists.

  9. After translating all the steps, run your code and verify it produces the right output.
    Hello out there!
    Enter a number as a percent: 10
    As a double the number is: 0.1
    
  10. Save double.cpp to turn in with the other lesson exercises for the week.

Testing your Work

  • Make sure to run your program as you add statements to implement your algorithm
  • Verify that your program does what you expected so far
  • If not, revise your algorithm to create the desired result
  • If you start to get frustrated, take a deep breath, or leave your screen for a minute
  • When you come back, you may see what was causing the trouble!
  • If you are still stuck, ask questions and try another approach
  • If you are still stuck after three attempts, consider getting help
  • Maybe one of your friends, a tutor or the instructor can point out where your plan goes awry
  • Be prepared to discuss your plan and show the steps you have already taken

Reflection

  • After solving the problem it is time to reflect and look back at what you have done
  • Look at what worked well and what did not work
  • Doing this will help you to predict what strategy to use to solve similar problems in the future
  • Ask yourself questions like:
    • Does your program solve the problem?
    • Did you reach all of the goals of this problem?
    • Now that you have one way to solve the program, is there an easier way to do it?
    • If you change this solution a little, will it work for any other programs?
    • Could you explain your solution to another person?

Check Yourself

  1. True or false: you should compile your code after adding every line or so to check for errors.
  2. True or false: after finishing your program, run the program to test it.
  3. True or false: the purpose of reflection after developing a program is to improve your problem solving ability.

2.4.5: Debugging Code

  • As we develop programs, we make errors
  • These errors are known euphemistically as "bugs" (See the first computer bug)
  • Grace Hopper, an early computer pioneer, popularized the term debugging
  • Often the error is because we left out a character or misspelled a word
  • In programming, one small mistake means the program does not work
  • The following are some types of errors we may encounter and what to do about them

Syntax Errors

  • One type of error is the syntax error or compile-time error
  • This means our source code violates the language rules
  • Some examples:
    cout << "Hello, World!\n"  // missing semicolon (;)
    cot << "Hello, World!\n";  // mispelled letters in cout command
    cout << "Hello, World!\n;  // missing closing "
    
  • The good news: our compiler finds the error and reports an error message like:
    fiddle.cpp: In function 'int main()':
    fiddle.cpp:13:5: error: expected ';' before 'cot'
         cot << "Hello, World!\n";
         ^~~
    
  • The message can tell us several import things but the most immediately useful is the line number
    fiddle.cpp:13:5: error: expected ';' before 'cot'
    
  • This tells us the approximate location of the error in the source code
  • Another useful part of the message is the error message itself
    fiddle.cpp:6: error: expected ';' before 'cot'
    
  • The message is trying to explain the problem but is often highly technical
  • You will get a sense of their meaning over time
  • In general, we should look at the first error or warning and ignore the rest
  • Often the first error or warning causes all the rest of the errors and warnings
  • For step-by-step instructions on debugging syntax errors, see: How To Debug Syntax Errors

Logic Errors

  • Another type of error is the logic error:
    • Logic errors are mistakes in the program's algorithm
    • Our program does not do what it is supposed to do
  • For example:
    cout << "Hell, World\n";
  • The compiler does not find these types of errors for us
  • Instead, we must run our program and look for errors in how it operates
  • Running a program and looking for errors is known as testing

Run-time Errors

  • A third type of error that we may encounter is the run-time error
    int x = 0;
    cout << 1 / x;
    
  • Run-time errors cause our program to exit with an abnormal error ("crash")
  • To find a run-time error we look in the first line of the stackdump file
    Exception: STATUS_INTEGER_DIVIDE_BY_ZERO at eip=00401228
    

Errors Versus Warnings

  • If we violate a syntax rule, the compiler gives us an error message
  • However, sometimes the compiler will give us a warning message instead
  • For example:
    erroneous.cpp:10:1: warning: "/*" within comment
  • This indicates that our code is technically correct
  • However, the code is unusual enough that it may be a mistake or is otherwise undesirable
  • Thus, you lose points for warning messages in your programming assignments

Preventing Bugs

  • The best way to debug is not to make bugs in the first place!
  • Start with a plan
  • Think about what you're writing before you write it--design first, code later
  • Compile frequently!
  • Execute (run the program) frequently!
  • Review before testing: Walk through your code mentally and try different values
  • Write readable code following the professional coding guidelines

More Information

Check Yourself

  1. True or false: one of the goals of testing is to find and correct errors.
  2. The program that tests if your program has a syntax error is known as a(n) ________.
  3. True or false: the hardest error to find is a syntax error.
  4. To test for logic or runtime errors, you must ________ your program.
  5. True or false: warnings are technically not errors so it is safe to ignore them.
  6. True or false: the best way to debug is not to write bugs in the first place.
  7. We should always compile after writing every line or two of code because ________.
    1. the compiler will tell you about syntax errors
    2. we know the location of any errors reported
    3. it is easier to prevent problems than correct them
    4. of all of these
  8. True or false: following a professional programming style makes it easier to see and prevent bugs.

Exercise 2.4: Debugging a Program

In this exercise we practice finding and fixing errors with a partner. Make sure you finished the previous activities as well so you can turn in:

Specifications

The following program was written by a person in a hurry. During the writing process a large number of errors were made.

Erroneous Program

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
    A very erroneous program.

    @author B. A. Ware
    @version 1.0 1/25/05

#include <iostrea m>
using namespace standard;

/**
 * The main functoin for the program.
 */
int main() {
    cout <<< "Hell out there.\";
    cout << "Enter a number as a percent: "
    cin << ware;
    Cout << "As a double the number is: ";
    cout << ware / 00 << end1;
    return;
}} / / end of main
Part A: Peer Review (3m)
  1. Find a partner for this exercise and create a text file named errors.txt
  2. Add a comment at the top of the file that contains the name of the person(s) with whom you reviewed the code, like:
    // Reviewed with Emma Programmer
    
  3. With your partner, review the program, finding and listing in your errors.txt file the line number and description of as many errors as you can within 3 minutes. For example:
    // Reviewed with Emma Programmer
    Line 6: missing closing comment symbols
    Line 7: space in iostream
    (more errors listed)
    
  4. Submit your list of errors to Canvas as part of next weeks assignment.
Part B: Syntax Errors (5m)

Find and correct the errors reported by the compiler by following the process described in How To Debug Syntax Errors.

  1. Copy and save the program code with the name: erroneous.cpp
  2. Find and correct the syntax errors or warnings reported by the compiler one at a time in order they appear.
  3. Submit your corrected program source code to Canvas as part of next weeks assignment.

Be prepared to answer the Discussion Questions when called upon.

Discussion Questions

  1. Did having someone review your code help find errors?
  2. What was the cause of the message, "warning: "/*" within comment"?
  3. Could the message, "warning: "/*" within comment", safely be ignored since it was just a warning?
  4. Did the list of errors reported by the compiler change dramatically as you corrected each one?
  5. Were the errors always on the line reported by the compiler?
  6. Did the compiler always find errors in the order in which the program code was listed?

2.4.6: Summary

  • Before starting to code you need a plan
  • The result of the plan is an algorithm that you translate to code
  • Even with a good plan, you will make errors as you develop code
  • One type of error is the syntax error or compile-time error where code violates the rules of the language
  • Another type of error is the logic error, where a program does not do what it is supposed to do
  • Yet another type of error is the run-time error
  • Run-time errors cause programs to exit with an abnormal error ("crash")
  • Sometimes the compiler will issue a warning if your code is unusual but still correct
  • You should treat this warning as an error because it is probably a logic error
  • Syntax errors are the easiest errors to find and correct
  • For instructions on solving syntax errors see How To Debug g++ Compile-time Errors

Review Questions

Answer these questions to check your understanding. If you are not sure, then follow the links to the section and review the material.

  1. What are the four parts of a computer? (2.4.1)
  2. What are the four parts of a computer program? (2.4.1)
  3. A sequence of precise instructions which leads to a solution is called an ________________. (2.4.1)
  4. What is the first thing we should do when developing a computer program? (2.4.2)
    1. Start typing C++ code into a text editor.
    2. Check our compiler to verify it is fully functional and up-to-date..
    3. Search the Internet to see if someone else has already solved the problem.
    4. Investigate and understand the problem we are trying to solve.
  5. What are two techniques we can use to help us understand a problem? (2.4.2)
  6. What are three good questions we might ask to help us understand a problem? (2.4.2)
  7. What is the result of developing a plan? (2.4.3)
  8. What four types of statements belong in most all programs? (2.4.3)
  9. What are three ways to think of how to solve a problem? (2.4.3)
  10. What is the relationship between an algorithm and a computer program? (2.4.4)
  11. What is the purpose of testing code that compiles without compile-time errors? (2.4.4)
  12. What are two kinds of programming errors? (2.4.5)
  13. What is a warning? (2.4.5)
  14. True or false: the best way to remove errors is not to write them in the first place (2.4.5)
  15. What is the importance of following professional programming style conventions? (2.4.5)
  16. In the following error message, what is the most immediately useful information? (2.4.5)
    fiddle.cpp: In function `int main()':
    fiddle.cpp:6: error: parse error before `return'
    
  17. Why should you ignore errors after the first one? (2.4.5)

Adios

Due Next:
A1-Getting Started (9/6/18)
Quiz 2 (Canvas) (9/11/18)
A2-Math and Memory (9/13/18)
  • When class is over, please shut down your computer
  • You may complete unfinished exercises at any time before the due date.
Last Updated: September 10 2018 @17:57:03