Lesson 2 Variables

Students will be able to:
• Declare and use variables
• Input integers
• Hold data
• Can be numbers, letters, words
• Place in main memory that holds the data
• Has a name that is assigned by the programmer
• int alice;
Type: int integer (whole number)
alice: name of variable
Variable is declared.
program to input an integer
and have it print out (echo)
#include <iostream>
using namespace std;
int main (void)
int alice;
cin >>alice;
cout<< “There is an echo “;
cout << alice;
Variable Names
• Can consist of numbers, letters, and underlines
• Can be as long as you like
Provided that:
• It starts with a letter
• It is unique for that program somewhere in the first 32
• Doug and doug are different
• Can’t be a keyword
Examples of variable names
• count
• Sum
• Salary,
• Next_character
• total
• reply
Type in and run the cin program. Make sure to
type a number in when you run the program
• What were the results:
• One way to assign a value to a variable is to input a
number from the keyboard like we just did in the last
• Another way is to use an assignment statement:
• int alice, bill;
declares variables
• cin>>alice
input number for alice
• bill = alice;
makes bill equal to alice
• cout<< bill;
prints out number inputted
Self Test: What do these lines
of code do?
• int Alice, Tom;
• cin >> Alice >> Tom;
• Alice = Tom;
• Tom = Alice;
• cout << Alice << Tom;
Answer goes here!
Self Test: What do these lines
of code do?
• int Alice, Tom, Save;
• cin >> Alice >>Tom;
• Save = Alice;
• Alice = Tom;
• Tom = Save:
• cout<< Alice << Tom;
Answer goes here!

similar documents