2: Basic Coding Skills

What We Will Cover


Continuations

Questions from last class or the Reading?

  1. What to do when Blackboard has problems
  2. Room Policies
  3. CodeLab Registration and Purchasing
  4. Tutoring resources

The Assignment Cycle

Most assignments (after the first) have three parts:

  1. Warm Up Exercises:
    • The first part is the warm-up exercises, which help prepare you for the problem-solving portion of the assignment
    • Warm-up exercises start with exercises we do in class and turn in to Blackboard
    • Then you complete several short review exercises, usually in CodeLab
    • CodeLab will tell you if you answered correctly and give you some hints if you make a mistake
    • Also, after you attempt the problem, you can try again and usually look at the answer in the Solutions tab
  2. Problem Solving Program:
    • The problem solving section lets you explore the concepts in a different way than the exercises
    • You will be given a problem and need to develop a solution
    • Acceptable solutions must meet a list of specifications

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

  3. Tutorial Exercises:
    • The tutorial exercises introduce 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, you can refer to the online lecture notes as they become available

Making choices

On a piece of paper and spend one minute writing the following lists:

  1. What are three things you choose to do?
  2. What are three things you have to do?

Homework Questions?

Homework Discussion Questions

  1. What is an algorithm for the assignment 1 problem?
  2. What was your experience installing Cygwin or the GCC/g++ compiler?
  3. Why do we need a compiler?
  4. What was your experience compiling the hello.cpp program?
  5. What was the hardest tutorial exercise? easiest?

2.1: Introduction to C++

Learner Outcomes

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

  • Describe how source code becomes a running program
  • Start a command-line session
  • Navigate directories from the command line
  • Compile and run C++ programs when given the source code
  • Display program output to the console

2.1.1: Programming Languages and C++

  • 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
  • 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++

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 B-yar-ne Strov-stroop at AT&T Bell Labs in the 1980s
    • 1979 - Stroustrup begins work on "C with Classes"
    • 1982 - Name changed to C++
    • 1983 - First used by AT&T
    • 1985 - First commercial use
    • 1988 - ANSI C++ standard released
    • 1998 - ANSI-ISO standard released (ISO/IEC 14882)
    • 2011 - Latest ANSI-ISO standard released (ISO/IEC 14882:2011)

Check Yourself

  1. True or false: computers can directly carry out C++ source code instructions.
  2. What are two advantages to programming in a high level language like C++?
  3. True or false: the ANSI standard for C++ was released after the ANSI standard for C.

More information

2.1.2: Writing a C++ Program

  • When we create a program, we first develop one or more algorithms
  • Once developed, we type the algorithms into a text file known as a source code file

    source code: instructions written in a programming language

  • The following example shows the source code for a very simple C++ program
  • The program simply displays a message on our computer's screen
  • We will go through the meaning of each line of code later
  • For now, we are going to focus on how to turn this source code into a program that runs on our computer

Example C++ Source Code

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

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

Entering and Saving Source Code

  • We can use almost any text editor to enter and save C++ source code
  • We use TextPad in the classroom and you can download it for use at home
  • We enter our source code into TextPad and save the file as: hello.cpp
    • Save the code to the Desktop directory
    • That way we can see our code files on our computer screen
  • Make sure you save the source-code file using the extension: .cpp
  • All C++ source code files must have the correct extension or the compiler program will not work

About Using IDEs

  • Many Integrated Development Environments (IDEs) are available for C++
  • IDEs typically provide visual tools for designing forms and debugging code
  • I do not recommend using an IDE while learning C++ because:
    • An IDE will generate code for you, which does not help you learn
    • IDEs are complex tools that themselves are difficult to learn
    • An IDE can distract you from your goal of learning C++
  • I do recommend using IDEs once you have a good understanding of C++:
    • Improves programmer productivity
    • Easier to develop user interfaces

Check Yourself

  1. True or false: source code is text written in a programming language.
  2. Our C++ source code files have the file extension ________.
  3. To write C++ source code you should use a(n) ________.

2.1.3: Introducing Our Compiler

  • After creating a source code file, we compile the source code into machine instructions using a compiler program
  • Several different C++ compilers exist
  • Unfortunately, they all have minor differences and "extensions"
  • Ideally, we want a compiler that will work the same on all three major operating systems:
    • Linux/UNIX
    • Mac OS X
    • Windows
  • Also, we want a compiler that is free on all these systems
  • To meet these requirements, we will use a compiler named: g++
  • You must use this compiler or you have a risk of your code not compiling when I test your program
  • If you use a different compiler and your code does not compile using g++, you will get a low score
    • Actually, your code must compile on g++ running under Cygwin
  • Note that the g++ compiler is installed in the CTC and other labs at Cabrillo

Installing g++

  • The g++ compiler comes installed on most Linux systems
  • Also, the g++ compiler is available free from Apple for their computers
  • The best way to install g++ on Windows is to install it with Cygwin
  • Cygwin is a set of free software tools that lets us run most UNIX programs on Windows
  • Its software includes the g++ compiler
  • You can easily install Cygwin on Windows, with g++ included, by following my instructions:
  • As part of its tools, Cygwin provides a UNIX-like shell (command line) environment
  • UNIX is an operating system that was written primarily in the C programming language
  • This command line environment works the same on Linux, Mac OS X computers and Windows computers with Cygwin installed
  • Windows users, in addition to Mac and Linux users, will need to use this command line in this course

Check Yourself

  1. The name of our compiler is ________.
  2. What is Cygwin and why do we use it?
  3. True or false: only Windows users need to install Cygwin.

2.1.4: Using Cygwin

  • We start Cygwin by selecting the Cygwin! Cygwin Bash Shell from the Start menu
  • To use Cygwin, we type commands at a command prompt
    $ ls
    • $ is the command prompt (do not type this)
    • ls is the command we type
  • After typing a command, we press the Enter key

Starting Cygwin

  • Select the Cygwin! Cygwin Bash Shell from the Start menu

Stopping Cygwin

  • At the command prompt, type exit

Stopping a Program

  • We can stop any program running under Cygwin by typing Ctrl-C
    (pressing the Ctrl and C keys at the same time)

Getting Help

  • Once we have a command line, we can use the UNIX help facility: man commandName
  • For example, to view the man(ual) page for the cat command:
    man cat
    
  • To quit viewing a man page, press the q (for quit) key

Navigating Directories

  • To get around in a file system, we need to navigate its directory tree
  • Everything in a file system is stored in a file
  • Files are grouped together into directories, also called folders
  • Directories are organized in a hierarchical structure starting at the root directory

    Directory tree

  • A path is the directories we must go through to get to the file we want
  • We can see this structure in the Windows explorer:
    • Right-click on the Start button
    • Select Explore from the list
  • The left-hand side shows the directory structure
  • The Address bar shows the path
  • At the command line, we only work with the path
  • We must understand directories and paths to work with our files

Navigation Using the Command Line

  • When the command line starts, we are located in our home directory
    • Our home directory depends on your computer
  • We can check the current directory path using pwd (print working directory)
    pwd
  • We can list the files in the current directory using ls
    ls
  • We can view the contents of a file using any of the commands: cat, more or less
    cat hello.cpp
  • We can change directory on our computer using the cd command
    cd Desktop
  • We can change to our home directory at any time by typing: cd ~
    cd ~
  • Change to any directory by typing: cd path
    cd /cygdrive/c/"Documents and Settings"/"All Users"/Desktop

    Note that Cygwin calls the C: drive: /cygdrive/c/

  • Change to a lower subdirectory level: cd directoryName
    cd Desktop
  • Change up one directory level: cd .. (change directory)
    cd ..
  • Change to the root of the file system: cd /
    cd /

Check Yourself

  1. To enter the following command on the command line, what do you type?
    $ ls
  2. To get help for C++ commands, enter ________ followed by the name of the command.
  3. To display the current directory in the terminal window, enter the command ________.
  4. To list all the files in the current directory, enter the command ________.
  5. To navigate to your home directory, enter the command ________.
  6. To navigate to a subdirectory named Desktop, enter the command ________.

More Information

2.1.5: Compiling and Running Programs Using g++

  • Now that we can use the command line in a terminal window, we will look at how to compile programs
  • This command for compiling a C++ program is:
    g++ -W -Wall -pedantic -o programName sourceFile.cpp
  • The command includes the compiler options:
    • -W: Print extra warning messages for some problems
    • -Wall: Enable all the warnings about questionable code
    • -pedantic: Show all the warnings demanded by strict ISO compliance
    • -o programName: place the executable output in programName
    • sourceFile.cpp: the name of our source code file
  • For example, to compile our hello.cpp file we would type:
    g++ -W -Wall -pedantic -o hello hello.cpp
  • This command produces the file hello.exe from the source file hello.cpp
  • When we type in this command, a whole series of steps take place
  • These steps are shown in the following diagram
  • We will look at these steps in more detail as the course progresses

Compilation Process

Compilation process

Running a Compiled Program

  • To run a program type ./ and its name after the command prompt
    ./programName
  • The operating system runs the file named programName.exe
  • Note that an .exe suffix is automatically appended
  • Thus, we do not need to type the .exe part of the program name

Step-By-Step Instructions for Compiling and Running hello.cpp

  1. Save your hello.cpp source-code file using TextPad in your Cygwin home directory.
    C:\Cygwin\home\yourHomeDirectory
  2. Start Cygwin

    Select the Cygwin Bash Shell from the Start menu. In the classroom, Cygwin is located in the CS & CIS submenu.

  3. Type the compile command:
    g++ -W -Wall --pedantic -o hello hello.cpp

    If no errors occur, the compiler creates the file: hello.exe. You can see this file by typing: ls

  4. At the command prompt type:
    ./hello

    You should see the program display a message.

Check Yourself

  1. Where should you save C++ source code files in the classroom?
  2. Where should you save C++ source code files on your home computer?
  3. What command do you type at the command line to compile a program named "foo.cpp"
  4. What command do you type at the command line to run the program you compiled in question 1?

More Information

Exercise 2.1

In this exercise we look at how to compile and run C++ programs in the classroom.

Specifications

  1. Work with no more than one other person on this exercise.
  2. Start TextPad and enter this code:
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, World!\n";
        return 0;
    }
    
  3. Save this code in a file named hello.cpp to the your Cygwin home directory:
    C:\Cygwin\home\yourHomeDirectory
  4. Start Cygwin by selecting the Cygwin! Cygwin Bash Shell from the Start menu.

    In the terminal window, also known as the console window, you can use commands like cd to change directories, ls to list files and pwd to print the working directory. For more information on the commands you can use see sections: 2.1.4: Using Cygwin.

  5. In the command window, use the ls command to list all your files. You should see hello.cpp in the command window like the following:

    Cygwin ls

  6. Compile the hello.cpp program by typing the following command at the command prompt and then pressing the Enter key:
    g++ -Wall -W -pedantic -o hello hello.cpp
    
    After running the command, you should see a window like the following:

    Cygwin compiled

  7. To run the program you type:
    ./hello
    After running the command, you should see a window displaying, "Hello, World!", like the following:

    Cygwin saying hello

  8. In a second text file named compiling.txt, record your answers to the following questions:

    Q1: What do you type to compile a program named foo.cpp?

    Q2: What do you type to run the source code you compile with question 1?

  9. Submit compiling.txt to Blackboard as part of assignment 2.

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 2.1.6: Summary.

2.1.6: Summary

  • To write, edit and save source code, we use a text editor
    • Make sure to save the source-code file using the extension: cpp
  • To translate the source code to machine instructions, we use a compiler
  • The compiler we must use for this course is called: g++
  • The g++ compiler comes installed on most Linux systems
  • Also, the g++ compiler is available free from Apple for their computers
  • The best way to install g++ on Windows is to install it with Cygwin
  • Cygwin is a set of free software tools that lets us run most UNIX programs on Windows, including g++
  • You can easily install Cygwin on Windows, with g++ included, by following my instructions:
  • To compile programs, we must learn to use the command line
  • To compile a program, use the g++ command with appropriate options
    g++ -W -Wall -pedantic -o hello hello.cpp
  • To run a program, type ./ and its name after the command prompt
    ./hello

Check Yourself

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

  1. What are the advantages of programming in a high-level language? (2.1.1)
  2. What is a compiler? (2.1.1)
  3. What is source code? (2.1.2)
  4. What extension must you add to a C++ source code file name? (2.1.2)
  5. Why do we use text editors like TextPad for writing and editing source code rather than Word Processors like MS Word? (2.1.2)
  6. What is the name of the compiler you used to compile the hello.cpp source code file? (2.1.3)
  7. What compiler must you use for this course? (2.1.3)
  8. What does a compiler program do? (2.1.3)
  9. What do the following commands do? (Hint: try them) (2.1.4)
    1. cd
    2. ls
    3. pwd
    4. cat hello.cpp
    5. exit
  10. What file did the compiler produce? (Hint: use the ls command to list the files)
  11. We used the following command to compile our hello.cpp program. What does each word of the command do? (2.1.5)
    g++ -Wall -W -pedantic -o hello hello.cpp
    
  12. What is the difference between the steps for compiling in the classroom and compiling at home? (2.1.5)

2.2: 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.2.1: 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
    
    /**
     * 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 (prewritten 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.2.2: 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
    return /* 1 */ 0;
    

Programming Style: Block Comments

  • Block comments are the main way to document your code
  • You should 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 Jane User
        @version 1.0 8/20/03
     */
    
  • The grading of most programming projects includes checking the comments of our code
  • Put a comment like this in every source code file if you want full credit

Check Yourself

  1. What is the purpose of a comment?
  2. When should you add comments to your code?
  3. What are the two types of comments supported by C++
  4. What style of comment should you put at the top of each program file?

2.2.3: Statements and Whitespace

  • Statements are commands you 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 give 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 with many 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.2.4: 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

  • Every C++ program has one or more functions, including a main function 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

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 delimiters
  • C++ uses curly braces { } as delimiters for code blocks
  • Left brace { begins body of every function
  • Right brace } ends body of every function
  • All functions have associated blocks
  • However, as we will see later in the course, we can use blocks 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

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. A block is a section of ________ grouped together with curly braces.
  6. True or false: always indent within curly braces.

2.2.5: Using Libraries and Namespaces

  • In programming terms, a library is a collection of prewritten code we can use in your 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, this 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>
  • This is a library for console I/O
  • It allows us to use the word cout for sending data to a terminal screen
  • Other libraries exist for math, strings and more
  • Note that 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 things
    • We will discuss these "things" in more detail as the course progresses
  • 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 need 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 as iostream by writing ________.
  4. To tell the compiler to use the standard namespace write ________.

Exercise 2.2

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

Specifications

  1. Start your text editor and enter the following code:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    /**
     * 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++ -W -Wall -pedantic -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.

  10. Create a second text file named syntax.txt and record your answers to the Exercise Questions listed below.
  11. Submit both your hellome.cpp and syntax.txt files to Blackboard as part of assignment 2.

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

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 2.2.6: Summary.

2.2.6: 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()

Check Yourself

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

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

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

  • As we develop programs, we make errors
  • These errors are known euphemistically as "bugs" (See also: First Computer Bug or here)
  • 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
    • Our source code violates the language rules
    • Our compiler finds the error
  • Some examples:
    cot << "Hello, World!\n";
    cout << "Hello, World!\"

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. How can you tell if your program has a syntax error?
  2. What do you do to find logic errors in your program?
  3. Warnings are technically not errors; why should you pay attention to warnings anyway?
  4. What is the purpose of testing code that compiles without compile-time errors?

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

Check Before Compiling

  • Do not "compile, run, and pray"
  • When you write a section of code, check it over for anything you might have missed
  • Work through it by hand if you are not sure it will work
  • By preventing problems, you 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

  1. True or false: the best way to debug is not to write bugs in the first place
  2. What should you do after writing a section of code, even before compiling?
  3. What is the importance of following common programming style conventions?

2.3.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 program
    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 systax errors, see: How To Debug Syntax Errors

Check Yourself

  1. In the following error message what is the most immediately useful information?
    fiddle.cpp: In function `int main()':
    fiddle.cpp:6: error: parse error before `return'
    
  2. Why should you ignore errors after the first one?

More Information

Exercise 2.3

In this exercise we practice finding and fixing errors.

Specifications

The following program was written by a person in a hurry. During the writing process a large number of errors were made. You need to 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 following code as: erroneous.cpp
  2. Review the purpose of each line of code with another student in the class, noting any errors you see as you discuss the code.
  3. Find and correct the syntax errors reported by the compiler.
  4. Add a comment to the top of the file that contains the name of the person with whom you reviewed the code, like:
    // Reviewed with Jane Programmer
    
  5. Submit your corrected program source code to Blackboard as part of assignment 2.
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; // 10%
    return;
}} / / end of main

As time permits, review section 2.3.4: Summary below and be prepared to answer the Check Yourself questions.

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

Check Yourself

  1. What are two kinds of programming errors? (2.3.1)
  2. What is a warning? (2.3.1)
  3. What is the purpose of testing code that compiles without compile-time errors? (2.3.1)
  4. True or false: the best way to remove errors is not to write them in the first place (2.3.2)
  5. To prevent errors, what should you do after writing a section of code -- even before compiling? (2.3.2)
  6. What is the importance of following common programming style conventions? (2.3.2)
  7. In the following error message, what is the most immediately useful information? (2.3.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.3.3)

2.4: Memory Concepts

Learner Outcomes

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

  • Describe how programs store data in a computer's main memory
  • Write code for declaring variables and assigning them values

2.4.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 name, 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 ourself, "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, we would have to use memory just like Hal did

2.4.2: Computer Memory

  • All computer algorithms require the computer to store data
  • Computers store programs and data in an area called main memory

    Computer overview

Main Memory

  • Main memory is organized as a long list of memory locations
  • Each memory location contains zeros and ones
  • The contents of a memory location can change while a program runs
  • The smallest unit of memory is the Binary Digit or bit
  • A bit that can only be zero or one

Memory Location

  • Each memory location has eight bits, which are known as a byte
  • The memory address is the number that identifies a memory location
  • Some data is too large for a single byte
  • For instance, most numbers are too large for one byte
  • In these cases, the address refers to the first byte
  • The next few consecutive bytes store the additional bits for larger data

Memory structure

Check Yourself

  1. True or false: both computer programs and the data the program is using are stored in main memory.
  2. The smallest unit of memory is known as a _____.
  3. True or false: main computer memory is organized as a long list of bytes.
  4. To access a byte of memory, our program must know the memory ___________ of the data.

More Information

2.4.3: Memory Addresses and Variables

  • Computer data is stored in and retrieved from various places in main memory
  • Before high-level languages, memory was referred to by its address
  • Storing integers 45 and 12 would allocate memory like the following

    Memory addresses

  • It quickly becomes cumbersome to write such programs
    • We have to manually keep track of each location
    • We have to make sure locations do not overlap
  • Most people can remember a name more easily than a number
  • Thus, the logical thing to do is create a name for each data we want to store
  • Then we let the computer remember the address and size of the memory
  • We call these named locations variables, because the data in them can vary (change)

    Memory variables

  • Now our programs can use commands like these:
    num1 = 45;
    num2 = 12;
    total = num1 + num2;
    

Check Yourself

  1. What is a variable?
  2. Which is easier for you to remember: a name or a memory address?

2.4.4: Data Types

  • Recall that main memory stores data for a program
  • The data is stored in memory locations named by variables
  • Each variable can only store one type of data

    Data type: a set of values from which a variable may take its value

  • A data type is important because it tells the compiler how the programmer intends to use the data
  • For instance, we want some variables to store numbers and others to store text
  • We can think of a data type as a child's game where we match shapes to holes
  • C++ does not allow square data pegs in round memory holes

Matching shapes to holes

  • There are four general categories of basic data types in C++:
Category Explanation Examples
Integer Numbers without decimal points 123, -987
Floating-Point Numbers with decimal points 1.23, -0.01
Character Single letters, digits and special symbols 'A', '9'
Boolean Logical values true or false true, false
  • To specify a data type, we use a keyword that specifies the type
  • The most commonly used C++ data types are:
Type Bytes Use
char 1 All ASCII characters.
short 2 Short integers from -32,768 to 32,767.
int 4 Integers from -2,147,483,647 to 2,147,483,647.
long 4 Integers from -2,147,483,647 to 2,147,483,647.
unsigned 4 Integers from 0 to 4,294,967,295.
float 4 Single-precision, floating-point numbers from about E-45 to E38 with 6 or 7 significant digits.
double 8 Double-precision, floating-point numbers from E-308 to E308 with from 14 to 15 significant digits.
bool 1 A true or false value.
  • Note that the number of bytes used for storage depends on the system and compiler

Check Yourself

  1. Which general category does C++ data type int belong in?
  2. What is the difference between an int and a long?
  3. What is the difference between an int and an unsigned?
  4. What is the difference between a float and a double?

2.4.5: Declaring Variables

  • All C++ program variables must be declared before using them
  • A declaration statement both names a variable and specifies the type of data it can store
  • General syntax:
    dataType VariableName1, VariableName2, ...;
    
  • Where:
    • dataType: one of the C++ data types
    • VariableNameX: the name of the variable
  • For example:
    int num1, num2, total;
    long dateNum;
    float firstNum;
    double secNum;
    char letter;
    
  • When we declare a variable, the compiler sets aside memory space
  • However, the contents of the storage space is undefined until we assign a value
  • For instance, after we declare the following variable, what is its value?
    int dragons;
    

Naming a Variable

  • A variable name is a sequence of letters, numbers, or underscore characters
  • However, C++ has some limitations on variable names
  • Specifically, the first character must be either a letter or an underscore character ( _ )
    • Cannot be a number
    • A $ is allowed but its use is discouraged
  • Also, the variable name cannot be one of the C++ reserved words (keywords)
  • For a list of reserved words, see: C/C++ Keywords
  • Note that we cannot have spaces in a variable name
  • A space is NOT a letter, number or underscore character
  • Also, variable names are cAsE sEnSiTiVe
    • id, ID, iD and Id are all valid but different names

Programming Style: Variable Naming Conventions

  • Use meaningful names that are easy to remember
    • Well-chosen identifiers make it easier for other programmers (like the instructor) to understand your program
    • For example, the following is syntactically correct:
      a = b * c;
    • However, it hides the intent or meaning
    • Contrast this with:
      weeklyPay = hoursWorked * payRate;
    • This tells other programmers the intent and meaning of the code
  • Use a consistent naming style, one of the following two commonly-used styles:
    1. Start with a lower-case letter and use uppercase letters as separators. Do not use underbars ('_').
      int myVar
    2. Use all lower case letters and use underbars ('_') as separators.
      int my_var
  • You must be consistent and only use one style in a program.
  • The instructor's preference is the first style.

Check Yourself

Which of the following are valid variable names?

  1. int myHello2;
  2. int 2myHello;
  3. int My_HeLlO;
  4. int my hello;
  5. int _a_very_long_variable_name_that_is_hard_to_read;
  6. int hel-lo;

2.4.6: Assigning Values to Variables

  • After we declare a variable, we must assign it a value
  • Use the assignment operator "equals sign" (=)
    variable = expression;
  • Where:
    • variable: the name of the variables
    • expression: the data we want to store in the variable
  • An assignment statement assigns value of expression (right side) to the variable (left side)
  • The simplest expression is a literal value:
    length = 25;
    width = 17.5;
    
  • Numbers like 25 and 17.5 are called literal numbers, or just literals, because we literally write them in the usual way
  • In each statement above, the value on right is assigned to the variable on the left
  • We can assign results of more complex expressions to a variable as well
    total = num1 + num2;
    slope = (y2 - y1) / (x2 - x1);
    
  • The expression on the right is evaluated (computed) before assignment to the variable on the left
  • Values placed into a variable replace (overwrite) previous values
  • Reading variables from memory does not change them

Assigning Initial Values to Variables

  • Initial values may or may not be assigned when variables are declared:
    // These are not initialized when declared
    // and have unknown values
    int sum, number1, number2;
    
    // These are initialized when declared
    int sum = 0;
    int number1 = 5, number2 = 10;
    
  • Good programming practice: initialize variables when declared

Check Yourself

  1. True or false: the "equals sign" (=) is the assignment operator in C++.
  2. True or false: in an assignment statement, the value on the left is assigned to the variable on the right.
  3. Why should we initialize variables when we declare them?

2.4.7: Input and Output

  • Another way to enter data into a variable is to read it from the console
  • The input console (keyboard) 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

Output Using cout

  • cout sends data to the console, which is usually the terminal window
  • The "<<" takes data from the right-hand side and sends it to the console
  • Any data can be output to the console
    • Variables
    • Literals
    • Expressions (which can include all of above)
  • Each data item must be separated with a << operator
  • For example:
    int numberOfGames = 12;
    cout << numberOfGames << " games played.\n";
    
  • Three values are output:
    • The value of the variable numberOfGames
    • A literal string " games played."
    • A newline character
  • Note that we can display multiple values in one cout
  • In the above example '\n' is a special code for a newline character
  • A second way to output a newline is to use the object endl
  • For example:
    int numberOfGames = 12;
    cout << numberOfGames << " games played." << endl;
    

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 as follows:
    Enter number of dragons: _
  • Where the underscore above denotes where keyboard entry is made
  • Every cin should have a cout prompt before it

Check Yourself

  1. What does the following code display to the console?
    int numberOfGames = 12;
    cout << numberOfGames << " games played.\n";
    
  2. Why is it a good practice to prompt users before input?
  3. What are two ways to assign a value to a variable?
  4. True or false: the << and >> always point in the direction the data is moving.

Exercise 2.4

In this exercise, we explore how to use variables by writing 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 the 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.4.5: Declaring 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.4.7: 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.4.7: 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.4.4: 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 Blackboard as part of assignment 2.

Completed Program

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

code listing

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 2.4.8: Summary.

2.4.8: Summary

  • Computers store data and code in main memory
  • Variables are how we can store data in our programs
  • Variables can be assigned new values while our program executes
  • Variables must be declared before use.
  • To initialize a variable, declare a name and assign a value.
  • Simple assignment statements have a variable, equals sign and an expression:
    variable = expression;
  • The expression is computed before the assignment
  • 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;
    

Check Yourself

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

  1. Why do you need to store data when creating a program? (2.4.1)
  2. How is the main memory of a computer organized? (2.4.2)
  3. How do you store information in a computer's main memory? (2.4.3)
  4. Why are locations for storing data in main memory referred to by a name rather than its numerical address? (2.4.3)
  5. What is the purpose of a data type like int or double? (2.4.4)
  6. What data values can you store in each of the following data types? (2.4.4)
    1. int
    2. double
    3. char
    4. bool
  7. Which of the following are valid variable names? (2.4.5)
    1. int myHello2;
    2. int 2myHello;
    3. int My_HeLlO;
    4. int my hello;
    5. int _a_very_long_variable_name_that_is_hard_to_read;
    6. int hel-lo;
  8. What code would you write to declare an int variable named foo and assign it a value of 10? (2.4.6)
  9. What code would you write to display a variable named foo to standard output? (2.4.7)
  10. What code would you write to input data from the keyboard and store it in a variable named foo? (2.4.7)
  11. Why is it a good practice to prompt users before input? (2.4.7)
  12. What are two ways to assign a value to a variable? (2.4.7)

Wrap Up

Due Next:
A1-Introductions and Algorithms (2/16/12)
A2-Implementing an Algorithm (2/23/12)
  • When class is over, please shut down your computer
  • You may complete unfinished exercises at any time before the due date.
Home | Blackboard | Day Schedule | Eve Schedule
Syllabus | Help | FAQ's | HowTo's | Links
Last Updated: February 12 2012 @23:23:14