Monday, December 29, 2008

CPPB

SOURCE:WIKIPEDIA

Important Terms:

A variable is a named memory location which temporarily stores data that can change while the program is running.

A constant is a named memory location which temporarily stores data that remains the same throughout the execution of the program.

The type of a variable indicates what kind of value it will store.

The name of a variable is known as its identifier.

A variable can be given a value through an assignment statement.

C++ recognizes eleven built-in data types which are designated by reserved words:

char
short
float
long double
unsigned int
unsigned long

int
long
double
unsigned char
unsigned short


Variables of different types occupy different amounts of memory space and are described as having different sizes.

** The basic C++ types that are included in the AP Computer Science subset are int, double, bool and char.

Variables Most Often Used

Data Type

C++ Keyword

Stores

Bytes of Memory

Range of Values

Character

char

1 character

1

1 character

Short integer

short

Integers

2

-32,768 to 32,767

Integer

int

Integers

4

-2,147,483,648 to 2,147,483,647

Long Integer

long

Integers

4

-2,147,483,648 to 2,147,483,647

Float

float

Decimal values to 7 decimal digit precision

4

3.4e-38 to 3.4e38
positive and negative

Double

double

Decimal values to 15 decimal digit precision

8

1.7e-308 to 1.73e308
positive and negative

Boolean

bool

Boolean (Logical) values


True or False

Rules for assigning variables:

Assign short, int or long data types when you are sure a variable is an integer number (NO decimal points). While these three integer choices are available, based upon the size of the numbers you are using, we will be using only int.

Assign float or double when decimals are needed. We will primarily be using double, as suggested by the AP Computer Science subset.

Assign char if the variable will always contain ONE character of data. This means only one letter (or character).

The names of variables in the C++ language are referred to as identifiers. The best naming convention is to choose a variable name that will tell the reader of the program what the variable represents. Variables that describe the data stored at that particular memory location are called mnemonic variables.


Rules for naming variables:

Variable names in Visual C++ can range from 1 to 255 characters. To make variable names portable to other environments stay within a 1 to 31 character range.All variable names must begin with a letter of the alphabet or an
underscore( _ ). For beginning programmers, it may be easier to begin all variable names with a letter of the alphabet.After the first initial letter, variable names can also contain letters and numbers. No spaces or special characters, however, are allowed.Uppercase characters are distinct from lowercase characters. Using all uppercase letters is used primarily to identify constant variables. You cannot use a C++ keyword (reserved word) as a variable name.


Tip: Some programmers use an underscore in variable names to separate parts of the name, such as shipping_weight. Others prefer a “capital style” notation, such as shippingWeight to separate parts of the name.

NEVER use uppercase for every letter in a variable name, because uppercase names are reserved for constant variables.

Samples of acceptable variable names:

Samples of unacceptable variable names:

Grade

Grade(Test)

GradeOnTest

GradeTest#1

Grade_On_Test

3rd_Test_Grade

Declaring Variables

All variables must be declared before they can be used.

How to declare a variable:
1. Choose the “type” you need.
2. Decide upon a name for the variable.
3. Use the following format for a declaration statement:
datatype variable identifier;
4. You may declare more than one variable of the same type by separating the variable names with commas.
int age, weight, height;
5. You can initialize a variable (place a value into the variable location) in a declaration statement.
double mass = 3.45;


Variables that are not initialized are NOT empty. If you do not initialize your variables, they will contain junk (”garbage”) values left over from the program that last used the memory they occupy, until such time as the program places a value at that memory location.

Constant Variables

Using const you can define variables whose values never change. You MUST assign an initial value into a constant variable when it is declared. If you do not place this initial value, C++ will not allow you to assign a value at a later time. Constants cannot be changed within a program.

const int ageLimit = 21; //this value cannot be changed

C++ will allow you to declare a variable anywhere in the program as long as the variable is declared before you use it.
A good programming practice to develop is to declare variables at the top of a function. Declaring variables in this manner makes for easier readability of the program.


The equal sign (=) is used for assigning values to variables.
The format of an assignment is:
variable = expression;

The variable is a variable name that you defined in the program.
The
expression is any variable, numerical, literal, or expression that produces a data type that is the same as the variable’s data type.

Data may be placed in a variable when it is declared:
int grade = 98;

or data may be placed in a variable AFTER it has been declared
(at a point further down in the program):
int grade;

grade = 98;

Never put commas in numerical values that you assign to variables.
The following statement is invalid:
double sales = 87,463.95; //Don’t do this!!!!

Compound Operators:

C++ has its own shortcut syntax involving the placement of values into numerical variables. You should be able to recognize all possible codings.

x += y; is the same as x = x + y;
x -= y; is the same as x = x - y;
x *= y; is the same as x = x * y;
x /= y; is the same as x = x / y;
x %= y;
is the same as x = x % y;

While a powerful tool used to update variables, compound operators can be troublesome. In the order of operations, the compound operators have lower precedence than regular math operators. Check out these two examples:

int x = 42;
int value = 0;
value = value - x + 2;
cout //gives - 40

int x = 42;
int value = 0;
value -= x + 2;
cout//gives - 44

Be careful when using compound operators. Remember the operator precedence.

+

-

*

/

%

Addition

Subtraction

Multiplication

Division

Modulus (also called remainder)


Did you notice that there is no symbol for “exponent”?

The MODULUS Operator %

The modulus operator produces the remainder of dividing the first value by the second value. For example:

22 % 6 = 4 because 22 / 6 = 3 with a remainder of 4


When using Modulus,
BOTH operands MUST be INTEGER TYPES!!!!


Confusing DIVISIONS

Be careful when performing integer division. When dividing an integer by an integer, the answer will be an integer (not rounded).

Compare these divisions: (5 is an integer while 5.0 is a double)

Integer division

8 / 5 = 1

Double division

8.0 / 5.0 = 1.6

Mixed division

8.0 / 5 = 1.6

When an operation involves two types (as the mixed division shown above), the smaller type is converted to the larger type. In the case above, the integer 5 was converted to a double type before the division occurred.


The cout statement may be used to print the information stored in any variable location to the screen.
It is possible to intermix several types of variables into one
cout statement as seen below:






int num1 = 4;
double num2 = 6.5;
cout

or for easier reading:

cout

Numbers and/or computations may also be printed without variable names:

cout // prints 976 on screen

cout // prints 40 on screen

Formatting Output


The manipulators discussed on this page require the header file named
iomanip.h#include #include
Formatting output is important in the development of output screens which can be easily read and understood. C++ offers the programmer several input/output manipulators. Two of these I/O manipulators are setw( ) and setprecision( ).


The setw( ) manipulator sets the width of the field assigned for the output. It takes the size of the field (in number of characters) as a parameter.

For example, the code: cout
generates the following output on the screen (each underscore represents a blank space)

_ _ _ _ _R


The
setw( ) manipulator does not stick from one cout statement to the next. For example, if you want to right-justify three numbers within an 8-space field, you will need to repeat setw( ) for each value:
cout

The output will be (each underscore represents a blank space)
_ _ _ _ _ _ 2 2
_ _ _ _ 4 4 4 4
_ _ 6 6 6 6 6 6


The setprecision( ) manipulator sets the total number of digits to be displayed when floating point numbers are printed.

For example, the code: cout will print the following output to the screen (notice the rounding):

123.46

The setprecision( ) manipulator can also be used to set the number of decimal places to be displayed. In order for setprecision( ) to accomplish this task, you will have to set an ios flag. The flag is set with the following statement:

cout.setf(ios::fixed);

Once the flag has been set, the number you pass to setprecision( ) is the number of decimal places you want displayed. The following code:

cout.setf(ios::fixed);
cout
generates the following output on the screen (notice no rounding):

12.34567


Additional IOS flags:
In the statement:
cout.setf(ios::fixed);
“fixed” is referred to as a format option.

Other possible format options:

left

left-justify the output

right

right-justify the output

showpoint

display decimal point and trailing zeros for all floating point numbers, even if the decimal places are not needed.

uppercase

display the “e” in E-notation as “E” rather than “e”

showpos

display a leading plus sign before positive values

scientific

display floating point numbers in scientific (”E”) notation

fixed

display floating point numbers in normal notation - no trailing zeroes and no scientific notation

**Note: You can remove these options by replacing setf with unsetf.

Displaying Amounts of Money:
To get 5.8 to display as 5.80, the following lines of code are needed”
//display money
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout
c
out

All subsequent couts retain the precision set with the last setprecision( ). Setprecision( ) is “sticky.” Whatever precision you set, sticks with the cout device until such time as you change it with an additional setprecision( ) later in the program.

Using cin >>

We have seen how the double arrows (coutshow that the information is going “out” to the monitor. In a similar way, the double arrows (>>) of the cin (pronounced see-in) show characters flowing “into” the program. The arrows point the way.
When using
cin, it is always necessary to provide a variable to the right of the operator to receive the input.


Sample program:// sample program for cin
#include

int main(void)
{
int fleas;
cout > fleas;
cout

cin can accept more than one variable as follows:

cout > integer >> decimal;

You would enter the values by typing on a single line and leaving a space between them, or by typing them on separate lines and hitting ENTER after each entry.

Character Literals and Variables

Characters are always only ONE letter or ONE character.
Character literals always appear inside single quotation marks.
Define
char variables for character data.


// Example of character literals
#include
int main(void)
{
char first, middle, last;
first = ‘D;
middle = ‘O’;
last = ‘G’;
// Rest of program would follow

NOTE: Character variable can be initialized when the variable is declared:
char HonorGrade = ‘A’; //Declare and initialize

String Literals

A string literal is any alphanumeric enclosed in double quotation marks. All string literals end with a string-terminating zero (NULL). Visual C++ uses this string-terminating zero to determine the end of a string value.

Notice how the string literal “Dogs Rule!” would be represented:

D

o

g

s


R

u

l

e

!

\0


Warning! String literals that contain only numbers are NOT to be thought of as “true” numbers. They are simply strings of digits that cannot be used to perform mathematical calculations such as addition or multiplication. Calculations can be performed only on numeric data — never on string literals.




String Lengths

The length of a string is the number of characters up to but not including the null zero.

String

Length

“R”

1

“5″

1

“Wally”

5

“”

0

“My Computer”

11


Character literals ALWAYS have a length of one. There is no null zero terminator for character literals.

The letter ‘R’ as a character in memory:

R

The letter “R” as a string in memory:

R

\0

Storing Strings in Arrays

There are NO string variable types in the Standard C++ language. Instead, strings are stored in character arrays.

Think of an array as a big “box” subdivided into compartments. Each compartment in the array will hold the same type of variable. You may have worked with arrays (vectors/matrices) in mathematics. A character array can hold one or more character variables in a row in memory.

char dogName[10]; //dogName holds a string

dogName is the name of this array of characters. Brackets ( [ ] ) are always included after an array name to indicate the presence of the array and specify its array length. This array is 10 characters long. Character arrays may be filled at the time of declaration.

char dogName[10] = “Wally Dog”;

W

a

l

l

y


D

o

g

\0

[0]

[1]

[2]

[3]

[4]

[5]

[6]

[7]

[8]

[9]


NOTE: The elements of the array are subscripted, starting with the number zero.

NOTE: Be sure to make the array size large enough to hold the string AND its null-terminating character (\0). (There are 10 boxes needed to hold “Wally Dog”.)

NOTE: Never try to assign string values to character arrays using a regular assignment statement, except when you first declare the character array.

dogName[10] = “Wally Dog”; //WON’T WORK!!!!!!!!!!!

The Advanced Placement Computer Science (APCS) Committee is the committee responsible for creating the APCS Examination. They have created a variety of C++ tools, based on the C++ standard, for the beginning programmer. One such tool, features the creation of an apstring data type. The letters “ap” associated with these tools let you know that they are not part of your current C++ compiler, but were developed by the APCS Committee.

The AP* tool needed to use this new string variable is apstring.cpp, and this new variable is declared as being of type apstring. Using the type apstring is similar to using int, double, and char.

You must use #include “apstring.cpp”to have access to this special apstring data type. You must install the AP Classes in the “include” directory of your software before using them. A link to the AP Classes can be found on the C++ main (opening) page.

//sample program
#include
#include “apstring.cpp”

int main(void)
{
apstring CrewName; //declare variable

CrewName = “Neelix”; //initialize variable

return 0;
}


The use of the apstring class will eliminate all of the problems of dealing with character string arrays that we have seen. With the apstring class we can initialize string variables whenever and wherever we wish and the computer will automatically keep track of the length of the string.

AP* is a registered trademark of the College Entrance Examination Board,
which was not involved in the production of this web site.

More Than You Wanted to Know
About Floating Point Variables

“Why do I tend to get warnings when I declare float variables?”

Visual C++ defaults all floating point numbers to doubles. Since doubles are “larger” (or “smaller”) than floats and require 8 bytes (floats require 4 bytes), the program is most likely thinking that you are casting - forcing a variable to take on the properties of another type. It is trying to warn you that your “double” may lose some of its accuracy if changed to a smaller ranged type, such as a float.

Just remember: To Visual C++, any number with a decimal point is a double. Since the Advanced Placement Examination deals primarily with doubles, we also will concentrate on the use of doubles.

Floating point variables involved with integer division are often confusing.

Consider the following situation:

int slices; //representing slices of pizza at 375 calories per slice
float miles;
//representing miles needed to jog off the pizza calories
miles = (375 * slices / 100):

1. If you declare slices as an int, and use
miles = (375 * slices / 100);

you have integer division taking place on the right hand side, since 375 and 100 are ints. This integer calculation is completed and the result is placed into a float. You get a warning of possible loss of data due to the integer division (in this case). You get the WRONG ANSWER displayed.

2. If you declare slices as an int, and cast the right hand side
miles = float(375*slices/100);

you are forcing the machine to accept the value of the parenthesis as a float type. But the parenthesis is computed first and the integer division occurs. Now, there is no warning, but the WRONG ANSWER is displayed.

3. If you declare slices as a float, you have prevented “integer division” from occurring and the CORRECT ANSWER is displayed.

4. Suggestion: ALWAYS BE AWARE OF INTEGER DIVISION - AND AVOID IT!
In this case, declare
int slices, and double miles. Make the computation line
miles = (375.0*slices/100);

The simple addition of the .0 makes 375.0 a double and solves all of the problems of integer division occurring.

Clear as muddy water, isn’t it!!! :- )

C++ is a superset of C and offers all the advantages of a procedural language. You can write a C++ program filled with for loops and if statements just as you would in C. But C++ offers much, much more. C++ allows you to create objects. An object is sort of like a struct on steroids. Understanding the value of objects is the key to understanding the popularity of C++.

Understanding Object Programming

As its name implies, an object programming language allows you to create, interact with, and delete objects. Just as a variable is based on a type definition, an object is based on a class definition. First, you’ll declare a class, then you’ll define an object (or many objects) said to be members of that class. While a struct definition is limited to data elements only, a class definition can include both data elements (called data members) as well as function pointers (called member functions). To make this clearer, let’s start with a simple problem and see how we’d solve it using both structs and objects.

No comments:

Post a Comment