What We Will Cover
Continuations
Questions from last class or the Reading?
- What to do when Blackboard has problems
- Room Policies
- CodeLab Registration and Purchasing
- Tutoring resources
The Assignment Cycle
Most assignments (after the first) have three parts:
- 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
- Problem Solving Program:
- 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:
- What are three things you choose to do?
- What are three things you have to do?
Homework Questions?
Homework Discussion Questions
- What is an algorithm for the assignment 1 problem?
- What was your experience installing Cygwin or the GCC/g++ compiler?
- Why do we need a compiler?
- What was your experience compiling the
hello.cpp program?
- What was the hardest tutorial exercise? easiest?
^ top
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
|
^ top
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:
- Move memory location 40000 into register
eax
- Subtract the value 100
- 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:
- We still have to enter a great many primitive instructions to create a program
- The instructions change from one processor to another
Higher-level Languages
History of C++
- C developed by Dennis Ritchie at AT&T Bell Labs in the 1970s
- 1973 - UNIX kernel rewritten in C
- 1978 - K&R C specified based on the book The C Programming Language
- 1989 - ANSI C standard released
- C++ developed by Bjarne Stroustrup
at AT&T Bell Labs in the 1980s
- 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
- True or false: computers can directly carry out C++ source code instructions.
- What are two advantages to programming in a high level language like C++?
- True or false: the ANSI standard for C++ was released after the ANSI standard for C.
More information
^ top
2.1.2: Writing a C++ Program
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
- Windows: TextPad, Notepad, WordPad
- Linux/Unix: EMACS, XEmacs, VIM, pico, nano, ...
- Mac: TextEdit, BBEdit, Text Wrangler, ...
- More information: List of text editors
- 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
- True or false: source code is text written in a programming language.
- Our C++ source code files have the file extension ________.
- To write C++ source code you should use a(n) ________.
^ top
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
- The name of our compiler is ________.
- What is Cygwin and why do we use it?
- True or false: only Windows users need to install Cygwin.
^ top
2.1.4: Using Cygwin
- We start Cygwin by selecting the
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 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

- 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
Check Yourself
- To enter the following command on the command line, what do you type?
$ ls
- To get help for C++ commands, enter ________ followed by the name of the command.
- To display the current directory in the terminal window, enter the command ________.
- To list all the files in the current directory, enter the command ________.
- To navigate to your home directory, enter the command ________.
- To navigate to a subdirectory named Desktop, enter the command ________.
More Information
^ top
2.1.5: Compiling and Running Programs Using g++
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
- Save your
hello.cpp source-code file using TextPad in your Cygwin home directory.
C:\Cygwin\home\yourHomeDirectory
- Start Cygwin
Select the Cygwin Bash Shell from the Start menu. In the classroom, Cygwin is located in the CS & CIS submenu.
- 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
- At the command prompt type:
./hello
You should see the program display a message.
Check Yourself
- Where should you save C++ source code files in the classroom?
- Where should you save C++ source code files on your home computer?
- What command do you type at the command line to compile a program named "foo.cpp"
- What command do you type at the command line to run the program you compiled in question 1?
More Information
^ top
Exercise 2.1
In this exercise we look at how to compile and run C++ programs in the classroom.
Specifications
- Work with no more than one other person on this exercise.
- Start TextPad and enter this code:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!\n";
return 0;
}
- Save this code in a file named
hello.cpp to the your Cygwin home directory:
C:\Cygwin\home\yourHomeDirectory
- Start Cygwin by selecting the
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.
- 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:

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

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

- 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?
- 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.
^ top
2.1.6: Summary
Check Yourself
Answer these questions to check your understanding. You can find more information by following the links after the question.
- What are the advantages of programming in a high-level language? (2.1.1)
- What is a compiler? (2.1.1)
- What is source code? (2.1.2)
- What extension must you add to a C++ source code file name? (2.1.2)
- Why do we use text editors like TextPad for writing and editing source code rather than Word Processors like MS Word? (2.1.2)
- What is the name of the compiler you used to compile the
hello.cpp source code file? (2.1.3)
- What compiler must you use for this course? (2.1.3)
- What does a compiler program do? (2.1.3)
- What do the following commands do? (Hint: try them) (2.1.4)
cd
ls
pwd
cat hello.cpp
exit
- What file did the compiler produce? (Hint: use the
ls command to list the files)
- 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
- What is the difference between the steps for compiling in the classroom and compiling at home? (2.1.5)
^ top
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
|
^ top
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
^ top
2.2.2: Comments
Programming Style: Block Comments
Check Yourself
- What is the purpose of a comment?
- When should you add comments to your code?
- What are the two types of comments supported by C++
- What style of comment should you put at the top of each program file?
^ top
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
- Statements usually end in a ________.
- When writing code, we should limit our line lengths to ________ characters to make the code easier to read.
- True or false: the compiler ignores extra whitespace.
^ top
2.2.4: The main() Function and Blocks
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
- True or false: every C++ program has at least one function.
- A C++ function is ________
- A mapping of a domain value to a codomain value
- A named block of code that executes a series of statements
- A named block of code that returns a value for a given argument
- Any procedure that returns a value
- True or false: every C++ program has a
main() function.
- Every C++ program starts executing in the ________ function.
- A block is a section of ________ grouped together with curly braces.
- True or false: always indent within curly braces.
^ top
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
Check Yourself
- A library is a collection of ________ code.
- We use libraries in our programs to ________.
- We tell the compiler to use the library as iostream by writing ________.
- To tell the compiler to use the standard namespace write ________.
^ top
Exercise 2.2
In this exercise we examine the basic elements of a C++ program.
Specifications
- 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
|
- Save the file as "
hellome.cpp".
- 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.
- Run the code and verify you get the message, "Hello, World!"
$ ./hellome
Hello, World!
- Try changing the message to personally greet you with your own name, like the following:
Hello, Ed Parrish!
- 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.
- 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.
- 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.
- 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.
- Create a second text file named
syntax.txt and record your answers to the Exercise Questions listed below.
- Submit both your
hellome.cpp and syntax.txt files to Blackboard as part of assignment 2.
Exercise Questions
- Does a comment change the way that a program compiles or runs?
- 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.
^ top
2.2.6: Summary
Check Yourself
Answer these questions to check your understanding. You can find more information by following the links after the question.
- What is the purpose of a comment? (2.2.2)
- What styles of comments are allowed in C++? (2.2.2)
- What is a statement? (2.2.3)
- How can you tell which lines of a program are statements? (2.2.3)
- What statement do you use to print a message to the console window? (2.2.3)
- What is meant by the term "whitespace"? (2.2.3)
- Where does every C++ program start? (2.2.4)
- What code do you write for the
main() function? (2.2.4)
- How do you include libraries in your C++ programs? (2.2.5)
^ top
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
|
^ top
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
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
Errors Versus Warnings
Check Yourself
- How can you tell if your program has a syntax error?
- What do you do to find logic errors in your program?
- Warnings are technically not errors; why should you pay attention to warnings anyway?
- What is the purpose of testing code that compiles without compile-time errors?
^ top
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
- True or false: the best way to debug is not to write bugs in the first place
- What should you do after writing a section of code, even before compiling?
- What is the importance of following common programming style conventions?
^ top
2.3.3: Debugging Syntax Errors
- The name of the program
fiddle.cpp: In function `int main()':
- The function where the error occurs
fiddle.cpp: In function `int main()':
- The line number of the error
fiddle.cpp:6: error: parse error before `return'
- 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
- 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'
- Why should you ignore errors after the first one?
More Information
^ top
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.
- Copy and save the following code as:
erroneous.cpp
- Review the purpose of each line of code with another student in the class, noting any errors you see as you discuss the code.
- Find and correct the syntax errors reported by the compiler.
- 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
- 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.
^ top
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
- What are two kinds of programming errors? (2.3.1)
- What is a warning? (2.3.1)
- What is the purpose of testing code that compiles without compile-time errors? (2.3.1)
- True or false: the best way to remove errors is not to write them in the first place (2.3.2)
- To prevent errors, what should you do after writing a section of code -- even before compiling? (2.3.2)
- What is the importance of following common programming style conventions? (2.3.2)
- 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'
- Why should you ignore errors after the first one? (2.3.3)
^ top
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
|
^ top
2.4.1: Importance of Memory
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:
- Get the first number
- Get the second number
- Add the first and second number and assign it to sum
- 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
^ top
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

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

Check Yourself
- True or false: both computer programs and the data the program is using are stored in main memory.
- The smallest unit of memory is known as a _____.
- True or false: main computer memory is organized as a long list of bytes.
- To access a byte of memory, our program must know the memory ___________ of the data.
More Information
^ top
2.4.3: Memory Addresses and Variables
Check Yourself
- What is a variable?
- Which is easier for you to remember: a name or a memory address?
^ top
2.4.4: Data Types

- 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
- 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?
^ top
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
- Use meaningful names that are easy to remember
- Use a consistent naming style, one of the following two commonly-used styles:
- Start with a lower-case letter and use uppercase letters as separators. Do not use underbars (
'_').
int myVar
- 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?
int myHello2;
int 2myHello;
int My_HeLlO;
int my hello;
int _a_very_long_variable_name_that_is_hard_to_read;
int hel-lo;
^ top
2.4.6: Assigning Values to Variables
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
- True or false: the "equals sign" (=) is the assignment operator in C++.
- True or false: in an assignment statement, the value on the left is assigned to the variable on the right.
- Why should we initialize variables when we declare them?
^ top
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
Prompting Users
Check Yourself
- What does the following code display to the console?
int numberOfGames = 12;
cout << numberOfGames << " games played.\n";
- Why is it a good practice to prompt users before input?
- What are two ways to assign a value to a variable?
- True or false: the << and >> always point in the direction the data is moving.
^ top
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
- 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;
}
- 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
- 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
- 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
- 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
- Add code to display a prompt to the screen:
cout << "Enter the second number: ";
- Add a statement to input a new value for the variable and store it in memory:
cin >> num2;
- Declare a third variable of type double named
total and assign it the result of adding the two variable together:
double total = num1 + num2;
- Write another statement that displays the result of adding the two numbers together:
cout << "The sum of " << num1 << " and "
<< num2 << " is " << total << ".\n";
- Compile and run your program to make sure it works correctly.
- 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:

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 2.4.8: Summary.
^ top
2.4.8: Summary
Check Yourself
Answer these questions to check your understanding. You can find more information by following the links after the question.
- Why do you need to store data when creating a program? (2.4.1)
- How is the main memory of a computer organized? (2.4.2)
- How do you store information in a computer's main memory? (2.4.3)
- Why are locations for storing data in main memory referred to by a name rather than its numerical address? (2.4.3)
- What is the purpose of a data type like
int or double? (2.4.4)
- What data values can you store in each of the following data types? (2.4.4)
int
double
char
bool
- Which of the following are valid variable names? (2.4.5)
int myHello2;
int 2myHello;
int My_HeLlO;
int my hello;
int _a_very_long_variable_name_that_is_hard_to_read;
int hel-lo;
- What code would you write to declare an
int variable named foo and assign it a value of 10? (2.4.6)
- What code would you write to display a variable named
foo to standard output? (2.4.7)
- What code would you write to input data from the keyboard and store it in a variable named
foo? (2.4.7)
- Why is it a good practice to prompt users before input? (2.4.7)
- What are two ways to assign a value to a variable? (2.4.7)
^ top
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.
^ top
Home
| Blackboard
| Day Schedule
| Eve Schedule
Syllabus
| Help
| FAQ's
| HowTo's
| Links
Last Updated: February 12 2012 @23:23:14
|