Variables

8
CS111 Lab Variables Instructor: Michael Gordon

description

 

Transcript of Variables

Page 1: Variables

CS111 Lab Variables

Instructor: Michael Gordon

Page 2: Variables

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…

Page 3: Variables

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

Page 4: Variables

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

Page 5: Variables

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.

Page 6: Variables

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;

Page 7: Variables

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.

Page 8: Variables

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;