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. Update on TBA lab hours

Homework Questions?

Homework Discussion Questions (Thursday)

  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 4000 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. You 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 you write more readable code like:
    if (interestRate > 100) {
        cout << "Interest rate error";
    }
    
  • These high-level instructions are translated to machine instructions using a compiler

    compiler: a program that translates text (source code) into machine instructions

  • Another advantage of higher-level languages is you 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, you can recompile your 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)

More information

2.1.2: Writing a C++ Program

  • When you create a program, you first develop one or more algorithms
  • Once developed, you 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 your 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 your 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

  • You 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 you can see your code files on your 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

2.1.3: Introducing Our Compiler

  • After creating a source code file, you 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 you 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

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 Desktop.
  4. Start Cygwin by selecting the Cygwin! Cygwin Bash Shell from the Start menu.

    In the command 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 and 2.1.5: Navigating Directories.

  5. In the command window use the cd command to change the location of the command window to the Desktop:
    cd Y:\desktop
  6. 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

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

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

  9. 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?

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

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)
    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) (2.1.6)
  11. We used the following command to compile our hello.cpp program. What does each word of the command do? (2.1.6)
    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 (see instructions for compiling at home below) (2.1.6)?

2.1.4: Using Cygwin

  • To use Cygwin, you type commands at a command prompt
    $ ls
    • $ is the command prompt
    • ls is the command you type
  • After typing a command, you press the Enter key

Starting Cygwin

  • Select the Cygwin Bash Shell from the Start menu

Stopping Cygwin

  • At the command prompt, type exit

Stopping a Program

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

Getting Help

  • Once you have a command line, you 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

2.1.5: Navigating Directories

  • To get around in a file system, you 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
  • A path is the directories you must go through to get to the file you want
  • You 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
  • You must understand directories and paths to work with your files

Navigation Using the Command Line

  • When the command line starts, you are located in your home directory
    • Your home directory depends on your computer
  • You can check the current directory path using pwd (print working directory)
    pwd
  • You can list the files in the current directory using ls
    ls
  • You can view the contents of a file using any of the commands: cat, more or less
    cat hello.cpp
  • You can change directory on your computer using the cd command
    cd Desktop
  • You can change to your 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 /

More Information

2.1.6: Compiling and Running Programs Using g++

  • Now that we can use the command line 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 your source code file
  • For example, to compile our hello.cpp file you would type:
    g++ -W -Wall -pedantic -o hello hello.cpp
  • This command produces the file hello.exe from the source file hello.cpp
  • When you 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, you 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 the classroom, I suggest you save your file to the Desktop. You can see your file on the computer screen if you save it to the Desktop. At home you should save your files in your Cygwin home directory.

  2. Start Cygwin

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

  3. Change directory (cd) to where you saved your program source code.
    cd y:/desktop

    Note that at home, Cygwin will start in a different directory than at school. At home, Cygwin starts in the directory C:\cygwin\home\username where username is different for every computer. Thus, you cannot use cd y:/desktop at home. When using Cygwin at home, I suggest that you save your source code where Cygwin starts, which is: C:\cygwin\home\username

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

  5. At the command prompt type:
    ./hello

    You should see the program display a message.

More Information

2.1.7: Summary

  • To write, edit and save source code, you use a text editor
    • Make sure to save the source-code file using the extension: cpp
  • To translate the source code to machine instructions, you use a compiler
  • The compiler you 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 you 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, you 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

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 you can use anywhere in your 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

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
    
  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.
  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.
  8. Remove the directive using namespace std; and then try to recompile the code. Your program will not compile and you should get an error message.
  9. Add the directive using namespace std; back into your program and verify that it compiles.
  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;

Check Yourself

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

  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. How do you include libraries in your C++ programs? (2.2.4)
  8. Where does every C++ program start? (2.2.5)
  9. What code do you write for the main() function? (2.2.5)

2.2.2: Comments

  • Comments are ... comments -- notes to people reading the code
  • Comments are ignored by the compiler
  • You 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

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
     */
    
  • Put a comment like this in every source code file if you want full credit

2.2.3: Statements and Whitespace

  • Statements are the commands you give a computer in a programming language
  • 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 {}
    • Also, some commands start with a # sign
    • Commands starting with a # sign are called preprocessor directives
    • A preprocessor directive is a command to the compiler rather than a command in the program
  • You can see examples of typical 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 you can add extra whitespace to your code to make 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

2.2.4: Using Libraries and Namespaces

  • In programming terms, a library is a collection of prewritten code you can use in your programs
  • This saves you the effort of writing your 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, you add the include directive to your program
    #include <libraryName>
  • Technically, this is called a "preprocessor directive"
  • It executes before compiling, and copies a library into your 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, you assign names to things
    • We will discuss these "things" in more detail as the course progresses
  • You can only use a name once within a namespace
  • All standard libraries put their definition in the namespace: std
  • To use these standard names, you need the directive:
    using namespace std;
  • Thus, most of your programs will begin with two statements:
    #include <iostream>
    using namespace std;
    

2.2.5: main() Functions and Blocks

  • C++ programs are structured into subprograms called functions

    Function - a block of code that performs a task

  • Every C++ program has one or more functions
  • Every C++ application has a main function that is declared like this:
    int main() {
        // program statements go here
    }
    
  • Programs begin executing at the first line of the main() function
  • int means main returns a value of type int -- cover later
  • For now, mimic the first line of main

Blocks

  • C++ is known as a block-structured language
  • This means that most source code is contained 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, you can use blocks other places as well

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 you 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 your programs will begin with two declarations:
    #include <iostream>
    using namespace std;
    
  • Every C++ application starts with a function named main()

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 your programs

2.3.1: Errors and Error Messages

  • As you develop programs, you will make errors
  • These errors are known euphemistically as "bugs" (See also: First Computer Bug or here)
  • One type of error is the syntax error or compile-time error
    • Your source code violates the language rules
    • Your compiler finds the error
  • For example:
    cot << "Hello, World!\n";
    cout << "Hello, World!\"
  • Another type of error is the logic error:
    • Logic errors are mistakes in the program's algorithm
    • Your program does not do what it is supposed to do
  • For example:
    cout << "Hell, World\n";
  • The compiler does not recognize these types of errors
  • Instead, you must run your program and look for errors in how it operates
  • Running a program and looking for errors is known as testing
  • A third type of error, that you will encounter later in the course, is the run-time error
  • Run-time errors cause your program to exit with an abnormal error ("crash")

Errors Versus Warnings

  • If you violate a syntax rule, the compiler gives you an error message
  • However, sometimes the compiler will give you are warning message instead
  • For example:
    erroneous.cpp:10:1: warning: "/*" within comment
  • This indicates that your 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
  • There is one warning that often mystifies you when you first see it:
    erroneous.cpp:87:26: warning: no newline at end of file
    
  • To correct this warning, you need to add a blank line to the end of your file

Debugging Syntax Errors

  • To debug your programs you have to read the error messages
  • As you read them you need to extract the important information
  • For example, this error message tells you 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 you the approximate location of the error in the source code
  • In general, you 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

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 g++ Compile-time Errors.

  1. Save the following code as: erroneous.cpp
  2. Find and correct the errors reported by the compiler.
  3. 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
/**
 * 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.;
    return;
}} / / end of main

Check Yourself

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

  1. What are two kinds of programming errors? (2.3.1)
  2. What is a warning? (2.3.1)
  3. What is the most useful information you can extract from an error message? (2.3.1)
  4. What is the process for debugging syntax errors? (2.3.1)
  5. What is the purpose of testing code that compiles without compile-time errors? (2.3.1)

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

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 you have a friend, named Grace, and you want to remember her phone number: 555-2368
  • You can store your friend's phone number in your memory
  • You even give your friend's phone number a name, like "Grace's phone number"
  • You do not really know where in your brain you store Grace's phone number
  • However, whenever you need her phone number, you say to yourself, "What is Grace's phone number" and out pops 555-2368
  • Just like you store your friend's number in your memory, you can store it in a computer's memory
  • We store data in a computer program using a variable
  • A variable is 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 program 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

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 look like the following:
    num1 = 45;
    num2 = 12;
    total = num1 + num2;
    

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

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. What is the name of the technique used for storing data in a computer's 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)

2.4.4: Data Types

  • Recall that main memory stores data for a program
  • The data is stored in memory locations named by variables
  • However, different types of data is stored in different ways
  • For instance, the letter 'A' may look like: 01000001
  • Also, the number 65 may look like: 01000001
  • How does the computer know the meaning of 01000001?
  • You have to tell the computer how to interpret the data by declaring a data type

C++ Data Types

  • A data type tells your computer program how to interpret data
    • Specifies how many bytes are needed to store the data
    • Tells the computer the format of the data
  • There are four general categories of simple data types that C++ provides:
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, you 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
  • Which general category does C++ data type int belong in?
  • What is the difference between an int and a long?
  • What is the difference between an int and an unsigned?
  • 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 data type it can store
  • The data type specifies the size and format of the data
  • 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 you declare a variable, the compiler sets aside memory space
  • However, the contents of the storage space is undefined until you 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 you 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 as you code.
    • 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 ('_').
    2. int myVar
    3. Use all lower case letters and use underbars ('_') as separators.
    4. 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 you declare a variable, you must assign it a value
  • Use the assignment operator "equals sign" (=)
  • variable = expression;
  • 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 you literally write them in the usual way
  • In each statement above, the value on right is assigned to the variable on the left
  • You 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

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)
  • You 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, usually the display screen
  • 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 you 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
  • cout << "Enter number of dragons: ";
    int numberOfDragons;
    cin >> numberOfDragons;
    cout << "You entered " << numberOfDragons
         << " dragons\n";
    
  • Note that you 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

2.4.8: Summary

  • Computers store data and code in main memory
  • Variables are how you can store data in your programs
  • Variables can be assigned new values while your 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;
    

Wrap Up

Due Next:
A1-Introductions and Algorithms (2/19/09)
A2-Implementing an Algorithm (2/26/09)
  • When class is over, please shut down your computer
  • You may complete unfinished exercises at the end of the class or at any time before the next class.
Home | Blackboard | Announcements | Day Schedule | Eve Schedule
Course info | Help | FAQ's | HowTo's | Links
Last Updated: February 26 2009 @13:34:52