Welcome Back!

Announcements
  • Quiz 1 after the break
  • Reminder: Lab 2 due Friday

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.

Review Activity
1. True or False? When pair programming...
  • Two people will be working on one computer
  • One person is called the driver and one is called the helper
  • You can work alone up to 25% of the time
  • In special circumstances, 3 people can work together
2. With a partner, write a complete program to print the message Greetings, earthlings! to the console window

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
 Integer
 A whole number. No decimal point.
 106
 Floating Point Number
 A number with a decimal point.
 3.14
 Character Individual letters, digits and symbols
'A', '%', '9'
 Boolean True/False, 0/1, On/Off
 true, false



C++ Has a Variety of Data Types:

TypeBytesUse
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
  
Partner Activity: Remembering Things
  • Just like in real life, it is hard to do anything without being able to remember things.
  • For example, we cannot even do something as simple as adding two numbers together without using our memories.
  • I need a volunteer to come up to the front!
  • Imagine a conversation between Hal and Grace
  • Turn to a partner and read this short dialogue together.
  • One person should read Hal's part and one person should play Grace.
    HalHey Grace, I just learned to add two numbers together. 
    Gracew00t! 
    HalGive me a number. 
    Grace
    HalOK, give me a second number. 
    Grace
    HalOK, the answer for 2 + 3 is 5
  • What just happened here?
  • 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.

Displaying sum of two integers using two variables only in C programming


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

Variables

  • 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 as Labeled Boxes Analogy
  • You can think of computer memory like a series of labeled boxes located in a storage unit. 
  • When we put something inside a box, we need to write a label on the outside to recall what is inside the box.
Think of computer memory as a series of boxes in a storage unit. 
We need to put a label on each box to remember what is inside.
  • Bigger items will require a bigger box or multiple boxes and smaller items will require smaller boxes.
  • Later, when we go back to search for a particular item in one of the boxes, we look for the label on the outside to help us find the item we are looking for.
  • If we remove an item from a box, we can put the same kind of item back in the box without having to change the name.
    • e.g. In a box labeled "television," you can take out the old television and put a new one inside without having to cross out the label on the box.
  • The following image illustrates how you would store the integer value 22 in computer memory, inside of a variable named x.


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 CodeBlocks and create a new program called practice.cpp. Copy and paste the starter code into your program.


/**
* Name
* Section Information
*/

#include <iostream>
using namespace std;

int main()
{
    //declare your variables here
}

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; 

Activity 4.1: Area of a Football Field (10 pts)
  • Find a partner for pair programming.
  • Open up CodeBlocks.
  • Create a new file called football.cpp.
  • Put a block comment at the start of your program with your names and section information
  • Add the library and namespace information
  • Create a main function
  • Create a variable called length and assign it the value 360 (pro football fields are 360 feet in length)
  • Create a variable called width and assign it the value 160 (pro football fields are 160 feet in length)
  • Create a variable called area and assign it the value of length * width;
  • Run the program and verify that there are no errors.
  • Is this program satisfactory?
  • Now, alter the program to print out the value of the area
  • For example, you could print out the area like this:

The area of a professional football field is 57600 ft2

  • Submit your program to Catalyst. Note that each partner should submit.


Review:

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


Homework:
  • Lab 2 due this Friday at midnight
  • Assignment 4 due Tuesday at 3:20pm


~Have a Good Weekend!~