Digital Reference

Introduction to programming --- C++

VARIABLES
Digital Reference---Introduction to Variables

Types

Do you recall variables from your mathematics class? Well, in C++, variables are used in a similar manner. They represent values that are assigned to them. There are many kinds of variables. Here are some common ones:

int

int variables represent integer values that have an absolute value less than or equal to 32,767

double

double variables represent values that have a decimal point

long

long variables represent integer values that have an absolute value less than or equal to 2,147,483,647

char

char variables represent characters

bool

bool variables represent true or false; #include <bool.h> must be included in the preprocessor

Variable Assignments

To assign values to variables, give the type of variable and the variable name (also called the identifier). Here’s an example:

Let’s introduce an integer variable x:

int x;

x = 168;

Above we have just assigned the value 168 to the integer variable x.

An example assigning a number with a decimal to a variable:

double y;

y = 168.28;

Here the decimal value 168.28 is assigned to the double variable y.

Assigning a character to a variable:

char someletter;

someletter = `A’;

The letter A is assigned to the char variable someletter.

The name of the variable (a.k.a. identifier) needs to begin with a letter. It can consist of any letter, number, and the underscore. The length of the identifier is up to you!

Now we will show you what operators can be used to allow your program to do arithmetic calculations.

For addition, use +

For subraction, use –

For multiplication, use *

For division, use /

If you want to find the remainder from division, use the % symbol. This is called modulus division.

Whenever you perform calculations between two integers, you will have an integer result. This is likewise between two double values, resulting in a double value.

However, if you have an integer and a double value in a calculation, the result will be a double.

Logical Operators

&& and || are logical operators. && symbolizes "and" in C++. || symbolizes "or."

These logical operators connect Boolean expressions (expressions that are either true or false) together and can be used in the if statements, if-else statements, switch statements, do-while, and while statements, which will all be discussed later.

Here is a table showing the result of two Boolean expressions connected by logical operators:

EXPRESSIONS RESULTS

 TRUE && TRUE TRUE TRUE || TRUE TRUE TRUE || FALSE TRUE FALSE || TRUE TRUE FALSE && FALSE FALSE FALSE || FALSE FALSE TRUE && FALSE FALSE FALSE && TRUE FALSE

NEXT

Home
Overview
Variables
Conditions
Loops
Arrays
Functions
Files
User-Defined
Pointers
Credits
 BBS Discussion Search Be Informed: Join us Subscribe Unsubscribe

ThinkQuest Team C008294