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
- Update on TBA lab hours
Homework Questions?
Homework Discussion Questions (Thursday)
- 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 4000 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:
- You 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)
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
- You 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 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
^ top
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
^ 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 Desktop.
- Start Cygwin by selecting the
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.
- In the command window use the
cd command to change the location of the command window to the Desktop:
cd Y:\desktop
- 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.
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)
cd
ls
pwd
cat hello.cpp
exit
- What file did the compiler produce? (Hint: use the
ls command to list the files) (2.1.6)
- 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
- 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)?
^ top
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
^ top
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
More Information
^ top
2.1.6: 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, you 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 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.
- Start Cygwin
Select the Cygwin Bash Shell from the Start menu. In the classroom, Cygwin is located in the CS & CIS submenu.
- 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
- 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.
More Information
^ top
2.1.7: Summary
^ 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 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
^ 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
- 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.
- 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.
- 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.
- Add the directive
using namespace std; back into your program and verify that it compiles.
- 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;
Check Yourself
As time permits, be prepared to answer these questions as well. You can find additional information in the sections that follow.
- 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)
- How do you include libraries in your C++ programs? (2.2.4)
- Where does every C++ program start? (2.2.5)
- What code do you write for the
main() function? (2.2.5)
^ top
2.2.2: Comments
Programming Style: Block Comments
^ top
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
^ top
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
^ top
2.2.5: main() Functions and Blocks
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
^ top
2.2.6: Summary
^ 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 your programs
|
^ top
2.3.1: Errors and Error Messages
Errors Versus Warnings
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 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
^ 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 g++ Compile-time Errors.
- Save the following code as:
erroneous.cpp
- Find and correct the errors reported by the compiler.
- 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.
- What are two kinds of programming errors? (2.3.1)
- What is a warning? (2.3.1)
- What is the most useful information you can extract from an error message? (2.3.1)
- What is the process for debugging syntax errors? (2.3.1)
- What is the purpose of testing code that compiles without compile-time errors? (2.3.1)
^ top
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
^ 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
- 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:
- 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 program 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

More Information
^ top
2.4.3: Memory Addresses and Variables
^ 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:

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)
- What is the name of the technique used for storing data in a computer's 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
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?
^ 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 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
- Use meaningful names that are easy to remember as you code.
- 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
- 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
^ 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)
- 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
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
^ top
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;
^ top
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.
^ top
Home
| Blackboard
| Announcements
| Day Schedule
| Eve Schedule
Course info
| Help
| FAQ's
| HowTo's
| Links
Last Updated: February 26 2009 @13:34:52
|