Variables
-
Upload
michael-gordon -
Category
Technology
-
view
1.108 -
download
7
description
Transcript of Variables
CS111 Lab Variables
Instructor: Michael Gordon
What is a variable?
Variables are a means of storing data for
the program.
Variables come in different types and
store different kinds of information:
Integers (whole numbers)
Decimal numbers
Characters
And more…
Common Types
int – a positive or negative integer
double – a positive or negative decimal
char – a single character
bool – a true or false value
string – a string of text
The above names are case sensitive
Int, Double, Bool, or Char won’t work
Declaring a variable
To declare a variable, you write its type
and its name (which you give it).
Examples:
int students; could be an integer variable
that stores the number of students in a class
string name; could store the class title
bool full; could store whether the class is full
or not
Assigning values
We use the equal sign to assign values to
a variable. Examples:
students = 30;
name = “CS111”;
full = false;
Strings must be contained within double
quotes.
char variables must be contained within
single quotes.
Initializing
Sometimes we declare variables and then
later assign their values, but sometimes we
want to give an initial value right away.
This is called initializing. Examples:
int students = 30;
string name = “CS111”;
bool full = false;
More on variable names
C++ rules for variable names:
Must start with a letter, not a number
Must have NO space in it
No special characters (only letters,
numbers, and underscore).
Must not be a C++ keyword, such as: return,
if, else, int, double, etc.
Variable initializations
Illegal examples
String name = 45;
int count = 2.5;
char grade = B;
double = ‘3.14’;
bool = “False”;
Legal examples
string name = “45”;
int count = 2;
char grade = ‘B’;
double = 3.14;
bool = False;