Welcome Back!

Learning Objectives

By the end of today's lesson, you should know...
  • What kinds of data the computer can store in its memory
  • The four most common data types in C++ and what kind of data they represent:
    • int - whole number or integer data
    • bool - true or false values
    • double - numbers with a decimal point
    • char - character data
  • How computers store data in memory.
  • What is a variable.
  • How to name variables.
  • How to declare variables.
  • How to assign values to variables.
  • Quiz 1 after the break
  • Please see me at the break if you are still trying to add the class
  • How did it go installing Eclipse?
    • See me in office hours for some help installing Eclipse - bring your computer if you can!
  • Don't forget Lab 2 due tomorrow at midnight
    • Who registered on CodeLab?

Review Activity

1. With a partner, write a complete program to print the message Greetings, earthlings! to the console window.

2. Now add a second cout statement to print We come in peace. on the following line of the console.

  • What are the two ways to do this?
3. Add an inline comment (a comment on a single line) that states This program prints a greeting. Write this comment above int main() {

Introducing Data Types

What is a data type?
  • What is data?
    • Information produced or stored by the computer.
  • What is a type?
    • The kind of data.
    • For example, numbers vs letters.
  • Data types are important because the compiler treats different types of data differently:
    • What kind of operations can be performed. Ex: We can't add and subtract letters.
    • How much storage to allot. Numbers and letters are stored differently in memory.
    • We can think of a data type as a child's game where we match shapes to hole.
    • C++ does not allow square data pegs in round memory holes.

  • There are four basic categories into which each data type falls:

 Category Explanation Example
 A whole number. No decimal point.
 Floating Point Number
 A number with a decimal point.
 Character Individual letters, digits and symbols
'A', '%', '9'
 Boolean True/False, 0/1, On/Off
 true, false

C++ Has a Variety of Data Types:

bool1true or false value.
char1All ASCII characters.
short2Short integers from -32,768 to 32,767.
int4Integers from -2,147,483,647 to 2,147,483,647.
long4Integers from -2,147,483,647 to 2,147,483,647.
unsigned4Integers from 0 to 4,294,967,295.
float4Single-precision, floating-point numbers from about E-45 to E38 with 6 or 7 significant digits.
double8Double-precision, floating-point numbers from E-308 to E308 with from 14 to 15 significant digits.
  • Note that the number of bytes used for storage depends on the system and compiler

Group Activity: Name That Data Type!

Which of the 4 most common data types are the values below. Select int, double, bool or char.
  • 'A' is a(n) _____________________
  • -213.555 is a(n) ________________
  • 14 is a(n) _____________________
  • 14.0 is a(n) ____________________
  • false is a ______________________
  • '$' is a ________________________
  • -2147483647 is a ______________
  • true is a _______________________

Most Common Data Types:

Type            Memory Used            Example        Size Range            
    int                4 bytes                        10                    -2,147,483,648 to 2,147,483,647
    double        8 bytes                        10.5                  10e-38 to 10e38
    char            1 byte                           'c'                     not applicable
    bool            1 byte                           true                  not applicable

Storing Data In the Computer's Memory

  • Let us pretend that we have a friend, named Grace, and we want to remember her phone number: 555-2368
  • We can store our friend's phone number in our memory
  • We even give our friend's phone number a label, like "Grace's phone number"
  • We do not really know where in our brain we store Grace's phone number
  • However, whenever we need her phone number, we say to our self, "What is Grace's phone number" and out pops 555-2368
  • Just like we store our friend's number in our memory, we can store it in a computer's memory
  • We store data in a computer program using a variable

    variable: the name of a place to store data in a computer's memory

  • Just like we do not know where in our brain we store a phone number, we do not know where in computer memory we store data
  • We simply give it a name and let the compiler decide where to store the data

Computers Need To Remember Things, Too! 

Recall How Computer Memory Works:

  • 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


  • When we want to instruct a computer to store or retrieve data from its memory, we don't want to have to refer to the memory location in 1s and 0s.
  • Wouldn't it be nice if we could use a name or label for a location in memory?
    • Most people can remember a name better than a number.
    • We would rather remember a name than a memory location in 1s and 0s.
  • Fortunately, there is a way to give labels to the contents of memory addresses.
  • Variables are labels used to reference locations in computer memory.

We don't want to have to remember memory addresses like this:

Instead we would rather remember memory addresses like this:

  • In the above diagram, num1 is a variable that refers to the contents of memory address 1652num2 is a variable that refers to the contents of memory address 2548, and total is a variable that refers to the contents of memory address 45.
  • When we use variables, we let the computer remember the address and size of the memory, we just remember the name of the variable.

Variables by Analogy

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

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

  • We put names on a box
  • We put values inside of boxes
  • When we want to see the value inside a box we look at it with code like:
    cout << "The value stored in box a: " << a;
  • If we change the value of a variable, we are putting a new value in the same box, like:
    a = 2;
    Replacing the value stored in a with a new value (2)

  • Making a new variable and assigning one variable to another makes a copy of the value and puts it into the new box:
    int b = a;
    Box b now has the same value as a (2)

  • We now have two different boxes that have independent values

Variable Declarations

  • To create a new variable, you need to tell the compiler what kind of data to expect.
    • Different data types require different numbers of bytes to store
      • e.g. integers are stored in 2 bytes while doubles are stored in 4 bytes.
    • Different operations can be performed on different types of data
      • e.g. You can't add characters together, but you can add integers together.
  • You also need to give your variable a name.
  • Each variable declaration (statement) needs to be followed by a semi colon ; 
  • Let's look at some examples
double pi;
int numberStudentsClass;
bool is_answer_correct;
char grade;
bool tooCool4U;

  • 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

  • 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  my_height;

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
    • $ 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
    • idIDiD and Id are all valid but different names

Programming Style: Variable Naming Conventions

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

Group Activity: Variable Declarations

Open up Eclipse and create a new project called practice with a file called practice.cpp.

Inside this program create 5 new variables as follows:

  1. A variable to store distance from your house to De Anza college
  2. A variable to store your De Anza student id number
  3. A variable to store whether or not you are the coolest person on the planet
  4. A variable to store the first letter of your first name
  5. A variable to store the number pi
Be ready to share your answers with the class.

Assigning Values to Variables

  • Once we have specified the name and data type for a variable, we want to give it a value.
  • The value should match the data type.
  • We give a variable a value by using the = sign.
  • The variable name goes on the left side of the = sign.
  • The variable value goes on the right side of the = sign.
  • A semi colon ; always goes at the end of the statement.
variableName = expression;

  • where expression is the value we assign to the variable.
  • Below is an example of how to declare and assign a variable.

int numHorses;
numHorses = 12;
  • We can also combine the two statements above into one statement.

int numHorses = 12;

  • Either method is valid though the second option is preferred.

Group Activity Continued:

  • Let's practice by giving values to the variables that we declared in our last group exercise.
  • Be ready to write your examples on the board under the correct column: int, double, bool, char

Assigning Literals and Complex Expressions to Variables
  • The simplest expression is a literal value:
    length = 25;
    width = 17.5;
  • Numbers like 25 and 17.5 are called literal numbers, or just literals, because we literally write them in the usual way
  • In each statement above, the value on right is assigned to the variable on the left
  • We can assign results of more complex expressions to a variable as well
    total = num1 + num2;
    slope = (y2 - y1) / (x2 - x1);
  • The expression on the right is evaluated (computed) before assignment to the variable on the left
  • Values placed into a variable replace (overwrite) previous values
  • Reading variables from memory does not change them

Initializing 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
  • Variables can also change their values as the program progresses
    • Why are they called variables? Their content varies.
int myAge = 28;
//later in program... after one year passes
myAge = 29; 

Displaying Variables Using cout
  • To display the contents of a variable using cout, the variable should first be declared and have been assigned a value.

cout << myAge; //NO!

int myAge = 12;

  • To display the variable, place the name of the variable after the <<.

         int myAge = 12;

cout << myAge;

  • It is also possible to print a message along with the variable contents by using the << operator to connect the variable to the message:

int myAge = 12;

cout << "I am " << myAge << " years old.";

Activity 4.1: My Weekly Salary (10 pts)
  • Find a partner for pair programming.
  • Open up Eclipse.
  • Create a new project called Salary with a new file called salary.cpp
  • Alter the block comment at the start of your program to include both partners' names and section information. For example
Jennifer Parrish
Georg Albrecht
  • Declare a variable called hours and assign it the value 40.
  • Declare a variable called wage and assign it a value of your choice.
  • Declare a variable called salary and assign it the value of hours * wage;
  • Run the program and verify that there are no errors.
  • Is this program satisfactory?
  • Now, alter the program to print out the values of the salary you calculated.
  • For example, you could print out the salary like this:

My weekly salary is $600.

  • Submit your program to Canvas.

  • With a Partner, review our learning objectives.
  • Answer the following question:

What Gets Printed to the Screen?

//assume below statement are part of a main function

int oranges = 5;

int apples = 8;

int numFruit = apples + oranges;

cout << "Total Fruit: " << numFruit << endl;

oranges = oranges + 1;

apples = oranges;

cout << "Apples: " << apples << endl;

    cout << "Oranges: " << oranges << endl;

  • Lab 2 due this Friday at midnight
  • Assignment 4 due Thursday at 9:20am

~ See You Thursday! ~