ADVANCED PLACEMENT Computer Science - C++ Lesson 2 - Data Types in C++

INTRODUCTION:               As with most high level languages, C++ provides standard data types to store information.  C++ is a richly typed language which gives the programmer a wide variety of data types to use.  In this lesson you will declare variables, store values in them, and print out their values using the cout object in the iostream.h library.

The key topics for this lesson are:

A.  Identifiers in C++

B.   Basic Data Types in C++

C.  Declaring and Initializing Variables in C++

D.  ASCII Code Values and Character Data

E.   Printing Variables Using cout

F.   Assignment Statements and Math Operators

 

VOCABULARY:                 

IDENTIFIER       KEYWORDS TYPE CONVERSION
INTEGER FLOAT ASSIGNMENT STATEMENT
CHAR   ASCII MODULUS  
ESCAPE SEQUENCE TYPE BOOL

DISCUSSION:                       A.  Identifiers in C++

1.   An identifier is a name which will be used to describe functions, constants, variables, and other items.

2.   The rules for writing identifiers in C++ are:

a.   Identifiers must begin with a letter.

b.   Only letters, digits, or underscore may follow the initial letter.

c.       The blank space cannot be used.

d.      Identifiers cannot be reserved words.  Reserved words or keywords are identifiers reserved for system use.

See Handout H.A.2.1, Reserved Words in C++.

 

3.   Most C++ compilers will recognize the first 32 characters in an identifier.  Also, C++ is a case sensitive language.  C++ will distinguish between upper and lower case letters in identifiers.  Therefore:

      grade versus Grade are different identifiers

 4.   A good identifier should also be a mnemonic device which helps describe the nature or purpose of that function or variable.  It is better to use

      grade instead of g,  number instead of n.

 5.   However, avoid excessively long or "cute" identifiers such as:

      gradePointAverage or bigHugeUglyNumber

      Remember that our goal is to write code which is easy to read and professional in nature.

 6.   Programmers will adopt different styles of using upper and lower case letters in writing identifiers.  The reserved keywords in C++ must be typed in lower case text, but identifiers can be typed using any combination of upper and lower case letters. 

7.   The following conventions will be used throughout the curriculum guide:

 a.   A single word identifier will be written in lower case only.  Examples:  grade, number, sum.

b.   If an identifier is made up of several words, the first letter will be lower case.  Subsequent words will begin with upper case.  Some examples are:  stringType, passingScore, largestNum.

c.   Identifiers used as constants will be fully capitalized.  Examples:  PI, MAXSTRLEN.

 B.   Basic Data Types in C++

1.   C++ provides four basic data types:  integer, character, floating point (real numbers), and a bool type.  The bool type is a recent addition to the C++ language and may or may not be included in your computing environment.

 2.   Integer and real numbers can also be modified with type qualifiers:  short, long, double, and unsigned.

 3.   Integer type - any positive or negative number without a decimal point.

 a.   Examples:  7, -2, 0, 2025.

b.   Short int and int are usually the same size in C++ systems, 2 bytes.

c.   Long int stores integers using 4 bytes.

d.   The following table summarizes the bytes allocated and the resulting integer size.  Note, these numbers are system-dependent.

 

 

Bytes Allocated

Smallest Integer

Largest Integer

 

int/short int

2 bytes

-32768

32767

long int

4 bytes

-2147483648

2147483647

unsigned int

2 bytes

0

65535

unsigned long int

4 bytes

0

4294967295

4.   The largest and smallest constants for each integer type are stored in the file limits.h.  These will be further explained and utilized in L.A.2.2, Math.

5.   Character type - letters, digits 0..9, and punctuation symbols.

 a.   Examples: 'A', 'a', '8', '*'

b.      Note that a character type must be enclosed within single quotes.

c.       Character types are stored using 1 byte, usually according to the ASCII collating sequence.  ASCII stands for American Standard Code for Information Interchange.

 

See Handout H.A.2.2,

ASCII Characters - A Partial List.

d.   The character value 'A' is actually stored as the integer value 65.  Because a capital 'A' and the integer 65 are physically stored in the same fashion, this will allow us to easily convert from character to integer types, and vice versa.

e.   Using the single quote as a delimiter leads to the question about how to assign the single quote (') character to a variable.  C++ provides escape sequences for unusual keystrokes on the keyboard.  Here is a partial list:

 

Character         C++ Escape Sequence
Newline    \n
Horizontal tab  \t
Backslash \\
Single quote  \'
Double quote  \"
Null character \0

6.   Floating Point type - any signed or unsigned number with a decimal point.

a.   Examples:  7.5      -66.72     0.125     5.

b.   A floating point value cannot contain a comma or $ symbol.

c.   A floating point value must have a decimal point.

d.   Invalid examples:  1,234.56     $ 66.95     125     7,895

e.   Floating point values can be written using scientific notation:

      1625.  =  1.625e3        .000125  =  1.25e-4

f.    The following are the usual byte sizes of floating points:

      float - 4 bytes               double - 8 bytes               long double - 10 bytes

g.   The more bytes allocated to store a float, the greater the accuracy.

 

7.   The constants for the largest and smallest float and double float values are stored in the header file float.h.  Again these will be studied more in L.A.2.2, Math.

8.   Data types are provided by high level languages to minimize memory usage and processing time.  Integers and characters require less memory and are easier to process.  Floating point values require more memory and time to process.

 9.   Older C++ compilers do not provide a Boolean type to store true or false values.  Eventually C++ compilers will support a bool type and the AP exam will use the bool data type in test questions.  If your environment does not support a bool type, your instructor will supply a file, bool.h, to include in your C++ environment.  This will enable the declaration of bool variables and use of true or false values.

C.  Declaring and Initializing Variables in C++

1.   A variable must be declared before it can be initialized with a value.  The general syntax of variable declarations is:

               type            variableName;

2.   Variables can be declared near the top of the function or in the midst of writing code.  Variables can also be declared and initialized in one line.  The following example program illustrates these aspects of variable declaration and initialization.

Program 2-1

#include <bool.h>

main ()

{

        int   first = 5, second;           // first is declared and initialized
        double  x;
        char  c1;
        bool  done;
        second = 7;
        x = 2.5;
        c1 = 'T';
        done = false;
 
        int  sum = first + second;
        return 0;

}

a.   Multiple variables can be declared on one line.

b.   Initialization is accomplished with an equal (=) sign.

c.   Initialization can occur at declaration time or later in the program.  The variable sum was declared and used in the same line.

3.   Where the variables are declared is a matter of programming style.  Your instructor will probably have some preferences regarding this matter.

D.  ASCII Code Values and Character Data

1.   As mentioned earlier in section B. 4, a character value can easily be converted to its corresponding ASCII integer value.

2.   A character value is stored using one byte of memory, which consists of 8 bits of binary (0 or 1) values.

3.   The letter 'A' has the ASCII value of 65, which is stored as the binary value 01000001.  This is illustrated in the following program fragment:

letter = 'A';    // letter is of type char

cout << "letter = " << letter;

cout << "     its ASCII position = " << int (letter) << endl;

Run output:

letter = A    its ASCII position = 65

      The statement   int (letter)   is called a type conversion.  The data type of the variable inside of the parentheses is converted to the outer type, if possible.

4.   In C++, you can make a direct assignment of a character value to an integer variable, and vice versa.  This is possible because both an integer and a character variable are ultimately stored in binary.  However, it is better to be more explicit about such conversions by using type conversions.  For example, the two lines of code below assign position the ASCII value of letter .

char        letter = 'C';

int   position;

 

position = letter;                  //  This is legal, position now equals 67.

        vs.

position = int (letter); //  This is easier to understand.

More detail about type conversions follows in section F. 9.

E.   Printing Variables Using cout

1.   Printing the contents of variables to cout is a simple process.

Program 2-2

#include <iostream.h>

#include <bool.h>

main ()

{

        int  number = 5;
        char  letter = 'E';
        double   average = 3.95;
        bool  done = false;
        cout << "number = " << number << endl;
        cout << "letter = " << letter << endl;
        cout << "average = " << average << endl;
        cout << "done = " << done << endl;
        return 0;

}

Run output:

number = 5
letter = E
average = 3.95
done = 0;

2.   Note the distinction between sending a text constant,"number = ", versus a variable, number, to cout.  A bool variable will be printed out as its integer representation of true (1) or false (0).

3.   C++ provides an abundance of formatting tools which will be covered in Lesson 3.  These tools will allow you to set field widths, display a certain number of decimal places, left-justify numbers, and more.

F.   Assignment Statements and Math Operators

1.   An assignment statement has the following basic syntax:

          Variable = Expression;

a.   The expression can be a constant value such as 2, 12.25, 't'.

b.   The expression can also be a numeric expression involving operands (values) and operators.

c.   The  =  operator returns the value of the expression.  This means that the statement

      a = 5;

  also results in the value 5.  This allows for chaining of assignment operators.

      a = b = 5;

      The assignment operator (=) is right-associative.  This means that the above statement is really solved in this order:

          a = (b = 5);      // solved from right to left.

         Since (b = 5) returns the integer 5, the value 5 is also assigned to variable a.

2.   C++ provides 5 math operators as listed below:

+    Addition, as well as unary +
-     Subtraction, as well as unary -
*    Multiplication
/     Real and integer division
%   Modulus, remainder of integer division  


3.   The numerical result and data type of the answer depends on the type of operands used in a problem.

4.   For all the operators, if both operands are integers, the result is an integer.  Examples:

      2 + 3 = 5  (integer) 9 - 3 = 6  (integer)

      4 * 8 = 32 (integer)            11/2 = 5  (integer)

5.   If either of the operands is a float type, the result is a float type.  Examples:

      2 + 3.000 = 5.000  (float)   25 / 6.75 = 3.7037 (float)

a.   When an integer and a float are used in a binary math expression, the integer is promoted to a float value, then the math is executed.

b.   In the example 2 + 3.000 = 5.000, the integer value 2 is promoted to a float (2.000) and then added to the 3.000.

6.   The modulus operator (%) returns the remainder of integer division.  For example:

      10 % 3 = 1 2 % 4 = 2                     16 % 2 = 0

      The modulus operator can only be used with integers.

7.   Changing the sign of a value can be accomplished with the negation operator (-), often called the unary (-) operator.  A unary operator works with only one value.  Applying the negation operator to an integer returns an integer, while applying it to a float returns a float value.  For example:

      - (67) = - 67          - (-2.345) = 2.345

8.   To obtain the fractional answer to a question like 11/2 = 5.5, a type conversion must be applied to one of the operands.

      double (11)/2  results in 5.5

      The type conversion operators are unary operators with the following syntax:

      (type) operand        or         type (operand)

      Examples:

      (int) 2.75 results in 2    float (11) results in 11.0000

      int (2.3 * 3) results in 6            (double) 25/4 results in 6.25

      The type conversion operators have a higher precedence than the math operators.  To accomplish a type conversion, either the data type or the operand must be in parentheses.  Returning to our original problem

      double (11)/2         the type conversion operator has priority

            11.000/2          then we solve division

            5.5

9.      There is more to cover regarding operators in C++.  Topics such as math precedence and assignment operators will be covered in Lesson 4.

Pointers

  SUMMARY/REVIEW:         These early lessons have covered a great amount of detail regarding the C++ language.  At first you will have to memorize the syntax of data types, but with time and practice fluency will come.

ASSIGNMENT:                    Lab Exercise, L.A. 2.1, Practice

                                                Lab Exercise, L.A.2.2,Math