2: Basic Coding Skills

What We Will Cover


Continuations

Questions from last class or the Reading?

  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. Quiz next week on compiling and running programs as well as other programming concepts

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?

  • A1-Getting Started (9/7/17)
  • What was your experience installing Cygwin or the GCC/g++ compiler?
  • What was your experience compiling the hello.cpp program?
  • Any problems with CodeLab?

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
  • 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:
    mov 40000, %eax
    sub 100, %eax
    jg 11280
    
  • 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 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++

  • C developed by Dennis Ritchie at AT&T Bell Labs in the 1970s
    • 1973 - UNIX kernel rewritten in C
    • 1978 - K&R C specified based on the book The C Programming Language
    • 1989 - ANSI C standard released
  • C++ developed by Bjarne Stroustrup at AT&T Bell Labs in the 1980s

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
  • We 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
  • 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, ________ indicates that a single line of commentary will follow it?
    1. /*
    2. /**
    3. //
    4. */
  3. You add comments to your C++ code to ________
    1. to explain unusual or obscure code
    2. to explain the purpose of a C++ file
    3. to explain how to use a function
    4. to explain all of the above
  4. Of the following, ________ should be used at the top of each programming project.
    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
  • We place C++ statements inside of functions like main()
  • 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!
    
  • Statements usually end in a semicolon (;)
  • However, some statements have blocks denoted by curly braces {}, such as if and while, which we will discuss later
  • 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 we give to the compiler rather than a command in the program
  • We can see two examples of statements in the program listing below
#include <iostream>
using namespace std;

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

Whitespace

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

Programming Style: Line Length

  • You should not make your statements too long or they are hard to read
  • When you write statements, limit your line length to 80 characters
  • Longer lines can cause problems in many terminal windows, text editors and other programming tools

Check Yourself

  1. Statements usually end in a ________.
  2. When writing code, we should limit our line lengths to ________ characters to make the code easier to read.
  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 -- cover later
  • For now, mimic the first line of main

Sequence

  • Within a function, code runs from top to bottom in a continuous sequence
  • Thus the two statements in main() are executed in sequential order
    cout << "Hello, World!\n";
    return 0;
    
  • First the computer prints "Hello, World!\n"
  • Then the computer exits the program with a return statement in main()
  • The order that programming statements are executed is important

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

  • We should always indent our statements inside braces
  • This makes the structure of our code easier to follow as our programs grow more complex
  • When we get to the end of a function, we 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 in the ________ function.
  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 directive to our programs
    #include <libraryName>
  • Technically, #include is called a "preprocessor directive"
  • It executes before compiling, and copies a library into our program file
  • 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
  • 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 part of programming, we assign names to parts of code
  • We can only use a name once within a namespace
  • All standard libraries put their definition in the namespace: std
  • To use these standard names, we add the directive:
    using namespace std;
  • Thus, most of our programs will begin with two statements:
    #include <iostream>
    using namespace std;
    

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 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 -std=c++11 -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. 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

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 give our friend's phone number a label, 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

  • The main feature that separates computers from other machines 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 with a range from -2,147,483,648 to 2,147,483,647.
double 8 Double-precision, floating-point numbers with 14 to 15 significant digits, +/- range, and exponents from 10-308 to 10308.

Assignment

  • After we declare a variable, we must assign the variable a value
  • To assign values, we use an assignment operator, which is an "equals sign" (=)
  • The assignment is made in an assignment statement in this form:
    variable = expression;
  • Where:
    • variable: the name of the variables
    • expression: the data we want to store in the variable
  • An assignment statement assigns the value of expression (right side) to the variable (left side)
  • 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
  • Good programming practice says we should assign a value when we declare a variable
  • Otherwise the value is undefined, though often 0, until the variable is assigned a value

Variables by Analogy

  • We can think of variables as boxes made of computer memory
  • A variable is just like a box that can hold a single thing
  • We need a way to tell one box from another so we give it a name
  • As we discussed, we can make up almost any name we want for the variable
  • For example, we declare a variable "a"
    int a;
    
  • When we first declare a variable the box is empty but has a name

    Empty box labeled a

  • Storing values in a variable is like putting items in a box
  • For example, we assign the variable "a" the value 1
    a = 1;
    
  • We can think of the above statement as putting the value 1 in a box with the variable name "a", like the one shown below (images source: David Goodger)

    value 1 in box a

  • 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:
    a = 2;
    

    value 2 in box a

  • 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

Try It: Code Variables (2m)

  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.

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 review these parts starting with output

Output

  • We have been using cout to display information on our video monitors
  • The command cout sends data to standard output, which is usually the terminal (console) window
  • The "<<" takes data from the right-hand side and sends it to the console
    cout << "Hello, World!\n";
    
  • Most basic data can be output to the console including
    • Variables (like num1)
    • Literals (like 12.34)
    • Expressions (which can include all of above)
  • 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." << endl;
    
  • Three values are output in order:
    1. The value of the variable numberOfDragons
    2. A literal string " dragons."
    3. An end-of-line (newline) character
  • In the above example endl is a special word for an end-of-line (newline) character
  • Notice that the last letter of endl is an "el" and not a one
  • Another way to output an end-of-line (newline) is to use "\n"
  • For example:
    int numberOfDragons = 3;
    cout << numberOfDragons << " dragons.\n";
    

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

Check Yourself

  1. The following code displays ________.
    int numberOfGames = 12;
    cout << numberOfGames << " games played.\n";
    
  2. Before getting input from a user, common practice is to display a(n) ________.
  3. 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.

I suggest that you 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() {
        // Enter your code here
    
        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;
    
  • Once declared, we can 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 '>>' points toward 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 but is not a literal integer
  • Literal numbers are constant and do not change while a program executes
  • Integers are usually stored in stored 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
  • Floating-point numbers are usually stored in stored 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

  • In the following examples, the fully parenthesized column shows the precedence explicitly
  • 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 )

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

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 the types 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 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
  • 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;
    
  • We can use modulus and integer division to translate integers to different bases as well
  • For example, to convert from decimal to binary we use the same technique but divide by and take the remainder of 2 instead

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

Check Yourself

  1. In division between two integer numbers, the remainder is ________.
    1. rounded up
    2. rounded off
    3. averaged
    4. truncated
  2. To compute the integer remainder we use the operator ________ .
  3. 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 eight (8) 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: Errors and Debugging

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: Errors and Error Messages

  • 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

Syntax Errors

  • One type of error is the syntax error or compile-time error
    • This means our source code violates the language rules
    • The good news: our compiler finds the error
  • Some examples:
    cot << "Hello, World!\n";
    cout << "Hello, World!\"
    
  • Common syntax errors include
    1. Missing semicolon (;)
    2. Misspelled letters in commands
    3. Missing curly braces
    4. Missing parenthesis
    5. Comments without comment symbols

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

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

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.

2.4.2: Preventing Bugs

  • It may sound obvious, but the best way to debug is to not write bugs into our code
  • Being careful with our code and design can take less time than tracking down a strange bug
  • The following are some bug-prevention techniques that will help us limit the number of bugs we produce

Start With a Plan

  • Have a plan before you start writting code
  • Develop a list of steps you think are required (an algorithm)
  • Once you have an algorithm then translate the steps to C++

Compile After Writing a Statement

  • The worst way to develop a program is write all the code before compiling
  • Trying to find all the errors becomes more difficult as the program grows larger
  • Instead, every time you write a line (or so) of code, compile your program
  • This way you know the location of the syntax errors

Review Before Testing

  • Do not "compile, run, and pray"
  • When we write a section of code, first check the logic of the algorithm
  • Work through the code mentally to check if it will work
  • If we already have an algorithm developed, we check the code conforms
  • By preventing problems, we will spend much less time fixing bugs

Write Readable Code

  • During the course we will discuss common style techniques used by professional programmers
  • By following these techniques, our code looks more professional
  • Also, following these techniques reduces the number of errors we produce
  • For instance, we discussed indenting code inside of curly braces
  • By indenting properly, our code is more readable by both ourselves and others
  • By formatting our code consistently, we can spot problems more easily and reduce errors

Check Yourself

Answer these questions and then verify your answers with your deskmate.

  1. True or false: the best way to debug is not to write bugs in the first place.
  2. 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
  3. After writing every section of code, always double check the conformance to the algorithm or ________.
    1. logic
    2. scope
    3. spelling
    4. syntax
  4. True or false: following a professional programming style makes it easier to see and prevent bugs.

2.4.3: Debugging Syntax Errors

  • Despite our best efforts we still create bugs in our code
  • To debug our programs we have to read the error messages
  • As we read them we need to extract the important information
  • For example, this error message tells us several important things:
    fiddle.cpp: In function `int main()':
    fiddle.cpp:6: error: parse error before `return'
    
  1. The name of the file
    fiddle.cpp: In function `int main()':
  2. The function where the error occurs
    fiddle.cpp: In function `int main()':
  3. The line number of the error
    fiddle.cpp:6: error: parse error before `return'
  4. The error description
    fiddle.cpp:6: error: parse error before `return'
  • The most immediately useful information is the line number
  • This tells us the approximate location of the error in the source code
  • 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

Check Yourself

  1. In the following error message, the most immediately useful information is the ________.
    fiddle.cpp: In function `int main()':
    fiddle.cpp:6: error: parse error before `return'
    
    1. error message
    2. file name
    3. function name
    4. line number
  2. True or false: generally, we should recompile after correcting the first error because the first problem may have caused all the error messages and compiling is fast.

More Information

Exercise 2.4: Debugging

In this exercise we practice finding and fixing errors with a partner.

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
/**
    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 << "My calculation is ";
    cout 1.0 / 0 << "%.."; // 1.0 / 10 = 10%
    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.
  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.4: Summary

  • As you develop programs, you will make errors
  • One type of error is the syntax error or compile-time error where your code violates the rules of the language
  • Another type of error is the logic error, where your program does not do what it is supposed to do
  • 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 probably is a logic error
  • Syntax errors are the easiest errors to find and correct
  • I provide some instructions for finding and correcting these errors in How To Debug g++ Compile-time Errors

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 are two kinds of programming errors? (2.4.1)
  2. What is a warning? (2.4.1)
  3. What is the purpose of testing code that compiles without compile-time errors? (2.4.1)
  4. True or false: the best way to remove errors is not to write them in the first place (2.4.2)
  5. To prevent errors, what should you do after writing a section of code -- even before compiling? (2.4.2)
  6. What is the importance of following common programming style conventions? (2.4.2)
  7. In the following error message, what is the most immediately useful information? (2.4.3)
    fiddle.cpp: In function `int main()':
    fiddle.cpp:6: error: parse error before `return'
    
  8. Why should you ignore errors after the first one? (2.4.3)

Wrap Up

Due Next:
A1-Getting Started (9/7/17)
A2-Math and Memory (9/14/17)
  • When class is over, please shut down your computer
  • You may complete unfinished exercises at any time before the due date.
Last Updated: October 08 2017 @15:57:47