Notes on C++
Home

These primitive and private ‘learning’ notes are not information or instruction for others
Many examples are straight out of Deitel and Deitel

Table of contents

Plan 3

References 3

Comments 4

Includes 4

Variables and identifiers. Data Types 5

The fundamental data types 6

Functions 7

Escape sequence 8

Demonstrating routine, #include, arithmetic, operations, assignment, main, return 0, cout, cin, declarations, integer, double, do, loops, while 9

A routine to illustrate while 10

A routine demonstrating new-style header files and namespaces 11

The exponential routine revisited. This version also demonstrates function prototype, function definition, and the if else structure 12

Multiple statements within an if, nested if, tailors output format to result 13

Experimenting with increment and decrement operators 15

Use of for repetition structure: calculating compound interest 17

Assignments and expressions. Assignment and relational operators 19

A routine that demonstrates counter controlled repetition 21

A routine that demonstrates sentinel controlled repetition and use of iomanip and static_cast 22

Use of switch multiple selection structure 24

Promotion hierarchy for built-in data types 26

Header files 27

C++ Keywords 29

Precedence and Associativity of C++ operators 30

Structured programming 32

Demonstrating cstdlib, ctime, rand, srand, enum 33

Storage classes and scope rules 35

Scope rules 36

Recursion – Fibonacci series 37

Functions with empty parameter lists 38

Inline functions, the const keyword and the #define preprocessor directive 39

Call-by-value and call-by-reference 40

Using constant reference parameters in a call-by-reference 41

References and reference parameters. Returning local variables 42

Default arguments 43

Unary scope resolution operator 44

Function overloading 45

Function templates 46

Pointers, strings and arrays 48

Arrays 51

Multidimensional or Multiple-Subscripted Arrays 53

Arrays as parameters (passing arrays to functions) 55

Arrays of pointers 56

Function pointers 56

Function pointers applied in menu driven systems 57

Character sequences 58

 

/*

Plan

      Update the plan

      Improve the reference list below

Update the precedence and associativity table (use the final table in

            Deitel and Deitel or other reference)

      Study the material by writing or copying routines

      Add headings and table of contents

 

      Consider, elaborate, minimize and modify the following order of study:

 

            Memory, types of memory, bits and bytes

            The ALU

                  16, 32, 64bit processors…

            I / O

            Data and data types

                  Identifiers and variables

                  Character, short, integer, long integer, float, double…

                        Boolean

                  Pointers, strings and arrays

            Identifiers; variables and literals

            Operators

                  Assignment…

            Expressions

            Functions

            Statements and comments; single and multiple line comments

                  lvalues and rvalues

            Programs

                  Console, batch, time-sharing, event-driven

                  Operating system, GUI

 

 

References

I have been using Deitel and Deitel’s ‘C++ How to to Program,’ second edition. At this point, 12/30/2006, I can tell that Deitel and Deitel is not best suited to my needs. I need something more systematic and precise with formal rather than informal explanations (perhaps the informal explanation helps a beginner feel comfortable and thus Deitel and Deitel or similar reference would be a useful supplement)

 

Some resources:

 

C++ Language Tutorial

Complete tutorial from cplusplus.com that covers from basics up to object oriented programming.

www.cplusplus.com/doc/tutorial

 

cplusplus.com - The C++ resources network

Information, Documentation, Reference, Sourcecodes and Forums about C++ programming language.

www.cplusplus.com/

 

C++ - Wikipedia, the free encyclopedia

The C++ programming language standard was ratified in 1998 as ISO/IEC ... In 1983, the name of the language was changed from C with Classes to C++. ...

en.wikipedia.org/wiki/C++

 

Visual C++ Developer Center

Product information, technical resources, samples and downloads, news and reviews.

msdn.microsoft.com/visualc/

 

Stroustrup: C++

Bjarne Stroustrup's information page about the programming language. Also contains links to other sites.

www.research.att.com/~bs/C++.html

Bjarne Stroustrup's Homepage

Developer of the C++ programming language.

www.research.att.com/~bs/homepage.html

 

C/C++ Reference

General C/C++. Pre-processor commands · Operator Precedence · Escape Sequences · ASCII Chart · Data Types · Keywords ...

www.cppreference.com/

 

GCC, the GNU Compiler Collection - GNU Project - Free Software ...

Developed by GNU project as free compiler for GNU system. Front ends: C, C++, Objective-C, Fortran, Java, Ada; libraries for libstdc++, and libgcj.

gcc.gnu.org/

 

Xerces C++ Parser

A validating XML parser written in a portable subset of C++ by the Apache project.

xml.apache.org/xerces-c/

 

C programming.com - Your Resource for C and C++ Programming

A Web site designed to help learning C or C++. Also provides C and C++ programming resources.

www.cprogramming.com/

 

*/

 

 

/*

Comments

multiple

line

comment

*/

 

 

// begin single line comment

 

 

/*

Includes

 

#include <iostream.h>

 

includes input-output stream functions e.g. cin, cout

int main() -- every C++ must have a main function

 

Why int? Because every function must be declared?

*/

/*

Variables and identifiers. Data Types

 

In this section, use has been made of Wikipedia and http://www.cplusplus.com/doc/tutorial/

 

A variable is a portion of memory to store a determined value

 

Variables are distinguished by their ‘identifiers’

 

Identifiers

 

A valid identifier is a sequence of one or more letters, digits or underscore characters that must begin with a letter or underscore (but not a digit)

 

Identifiers can begin with an underscore but this is usually reserved for compiler specific keywords or external identifiers

 

C++ is a case sensitive language

 

An identifier cannot be a C++ keyword. The standard reserved keywords are:

 

asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while

 

Additionally, alternative representations for some operators cannot be used as identifiers since they are reserved words under some circumstances

 

and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq

 

Individual compilers also have compiler specific keywords

 

Bytes

 

A byte is usually eight bits and is also called a ‘character.’ Sometimes (in what is now non-standard use) a byte may refer to four bits. The term ‘octet’ means eight bits and is preferable if ambiguity must be avoided

 

Words

 

In computing, “word” is a term for the natural unit of data used by a particular computer architecture; a word is a fixed-sized group of bits that are handled as a unit by the machine. Word size or word length is an important characteristic of a computer architecture

 

The size of a word is reflected in many aspects of a computer's structure and operation. The majority of the registers in the computer are usually word-sized. The typical numeric value manipulated by the computer is probably word sized. The amount of data transferred between the processing part of the computer and the memory system is most often a word. An address used to designate a location in memory often fits in a word

 

Modern computers usually have a word size of 16, 32, or 64 bits. Many other sizes have been used in the past, including 8, 12, 18, 24, 36, 39, 40, 48, and 60 bits; the slab is an example of an early word size. Some of the earliest computers were decimal rather than binary, typically having a word size of 10 or 12 decimal digits, and some early computers had no fixed word length at all

 

The most common microprocessors used in personal computers have the x86 architecture (for instance, the Intel Pentiums and AMD Athlons). The x86 family includes several generations of achitecture. In the Intel 8086, 80186, and 80286, the word size is 16 bits. In IA-32, the word size is 32 bits. In x86-64, the word size is 64 bits. Yet each implementation also implements the earlier instruction sets too. So Intel calls 16 bits a word in all of them; this usage of word is different from that above

 

The ‘slab’

 

A slab is the word in the NCR 315 computer architecture from NCR Corporation. It has 12 data bits and the parity bit. A slab may contain three digits (with at sign, comma, space, ampersand, point, and minus treated as digits) or two alphabetic characters. A slab may contain a decimal value from -99 to +999

 

A numeric value contains up to eight slabs. If the value is negative then the minus sign is the leftmost digit of this row. There are commands to transform digits into alphanumeric characters or inverse. All these commands use the accumulator which has a maximum length of eight slabs. To accelerate the processing the accumulator works with an effective length

 

The NCR 315 was the follow-on to the NCR 304

 

The fundamental data types

 

A byte can store a relatively small amount of data: one single character or a small integer (generally an integer between 0 and 255)

 

More complex data types are stored by grouping bytes

 

A byte is the smallest amount of memory managed in C++

 

Name and

Declaration

Description

Size*

Range*

char

 

here and

below, the default for

most

compilers

is signed

character or small integer

1byte

signed: -128 to 127
unsigned: 0 to 255

short int
(or short)

short integer

2bytes

signed: -32768 to 32767
unsigned: 0 to 65535

int

integer

4bytes

signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295

long int
(or long)

long integer

4bytes

signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295

bool

boolean value:

      true (any integer

      other than zero) or

      false (the integer 0)

1byte

true or false

float

floating point number.

4bytes

3.4e +/- 38 (7 digits)

double

double precision floating point number

8bytes

1.7e +/- 308 (15 digits)

long double

long double precision floating point number

8bytes

1.7e +/- 308 (15 digits)

wchar_t

wide character

2bytes

1 wide character

 

* The values depend on the architecture of the system. The values shown are those on most 32bit systems. For other systems, the general specification is that int has the natural size of (one word) suggested by the system architecture (one word) and each of the four integer types char, short, int and long be at least as large as the preceding type. Similarly,  each of the floating point types float, double and long double, must provide at least as much precision as the preceding type

 

Declaration of variables

 

All variables must be declared in C++

 

The following are equivalent

      signed int x;     // and

      int x;

 

      short int x;      // and

      short x;

 

      long int x; // and

      long x;

 

*/

 

*/

Functions

Begin and end character; escape character; return; cout and cin

// every function must end with "{"

      cout << "Welcome\n"; // \ is the escape character

     

      return 0; // indicates that the program ended successfully

}

//evey function must end with "}"

*/

 

 

/*

Escape sequence

 

Escape Sequence

Description

\n

New line

\t

Horizontal tab

\r

Carriage return without new line

\a

Alert. Sound system bell

\\

Used to print backslash

\"

Used to print double quote

*/

/*

Demonstrating routine, #include, arithmetic, operations, assignment, main, return 0, cout, cin, declarations, integer, double, do, loops, while

 

A routine to calculate the exponential function that demonstrates #include, arithmetic operations, assignment, main, return 0, cout, cin, declarations, integer and double types, do loops - if the condition is place at the head of the loop it is a while loop in C++ and, unlike other languages there is no ‘do while’

*/

 

#include<iostream.h>

 

int main()

{

      double error, x, term, sum;

      int I, N;

      do {

            cout << "enter x: ";

            cin >> x;

            cout << "enter error: ";

            cin >> error;

            I = 0;

            term = 1.0;

            sum = 0.0;

            do {

                  sum = sum + term;

                  I = I + 1;

                  term = term * x / I;

            } while (term > error);

            cout << "exp(x) = " << sum << endl;

            cout << "enter 0 to continue or 1 to stop ";

            cin >> N;

      } while (N < 1);

      return 0;

}

 

/*

A routine to illustrate while

*/

 

#include <iostream>

using namespace std;

 

/*

If new style headers are used, namespace std must also be used

Introducing do before while below does not work in C++

*/

int main()

{

      int i;

      i = 0;

      while ( i <= 10 ) {

            cout << i << endl;

            i = i + 1;

      }

      cout << endl;

      return 0;

}

/*

A routine demonstrating new-style header files and namespaces

*/

 

#include <iostream> // Most new-style header files do not end with h

 

using namespace std;

 

/*

Namespaces maintain unique names for different software components.

std is used by every header file in the C++ standard library to guarantee

that every feature is unique from other software components.

Programmers should not use namespace std to define new class libraries

*/

 

int main()

{

      int num1;

 

      cout << "Hello world!\n";

      std::cout << "Hello world!\n" << endl;

 

      cout << "Press any character key and enter to end." << endl;

      cin >> num1; // Prevents stand-alone use from exiting after execution

 

      return 0;

}

/*

The exponential routine revisited. This version also demonstrates function prototype, function definition, and the if else structure

 

Note also that there is a modification to compute the exponential for negative numbers which works only because exp- = 1 / exp and the nature of the error for the exponential function

*/

 

#include<iostream.h>

 

double absolute(double); // function prototype

 

int main()

{

      double error, x, term, sum;

      int I, N;

      do {

            cout << "enter x: ";

            cin >> x;

            cout << "enter error: ";

            cin >> error;

            I = 0;

            term = 1.0;

            sum = 0.0;

            do {

                  sum = sum + term;

                  I = I + 1;

                  term = term * absolute(x) / I;

            } while (term > error);

            if ( x < 0.0 )

                  sum = 1.0 / sum;

            cout << "exp(x) = " << sum << endl;

            cout << "enter 0 to continue or 1 to stop ";

            cin >> N;

      } while (N < 1);

      return 0;

}

 

// Function definition

double absolute(double y)

{

      double result;

      if ( y >= 0.0 )

            result = y;

      else

            result = - y;

      return result;

}

/*

Multiple statements within an if, nested if, tailors output format to result

 

A simple routine that uses multiple statements within an if and nested if and tailors output format to result. The routine also uses the relational operators == (is equal to) and != (is not equal to)

*/

 

#include <iostream.h>

 

int main()

{

      int num1, num2;

 

      cout << "Enter two integers on separate lines, and I will tell you\n"

             << "the relationships they satisfy:\n" << endl;

 

      cin >> num1 >> num2;

 

      if ( num1 == num2 )

 

            {cout << endl << "The following relationships exist between " <<                    num1 << " and itself " << endl << endl;

 

                  if ( num1 == num2)

                        cout << num1 << " is equal to itself " << endl;

 

                  if ( num1 <= num2)

                        cout << num1 << " is less than or equal to itself " <<                              endl;

 

                  if ( num1 >= num2)

                        cout << num1 << " is greater than or equal to itself "                              << endl;}

 

      cout << endl;

 

      if ( num1 != num2 )

 

            {cout << endl << "The following relationships exist between " <<                          num1 << " and " << num2 << endl << endl;

 

                  if ( num1 == num2)

                        cout << num1 << " is equal to " << num2 << endl;

 

                  if ( num1 != num2)

                        cout << num1 << " is not equal to " << num2 << endl;

 

                  if ( num1 < num2)

                        cout << num1 << " is less than " << num2 << endl;

 

                  if ( num1 <= num2)

                        cout << num1 << " is less than or equal to " << num2 <<                             endl;

 

                  if ( num1 > num2)

                        cout << num1 << " is greater than " << num2 << endl;

 

                  if ( num1 >= num2)

                        cout << num1 << " is greater than or equal to " << num2                             << endl;}

 

      cout << endl;

 

      return 0;

}

/*

Experimenting with increment and decrement operators

*/

#include <iostream>

using namespace std;

 

 

int main()

{

      int a, b, c, I, N;

 

      do {

            cout << "Enter a: "; cin >> a;

            cout << "Enter b: "; cin >> b;

            cout << "Enter c: "; cin >> c;

 

            cout << "Enter a number from 1 to 10: "; cin >> I; cout << endl;

 

            cout << "Initial values" << endl << "a = " << a << endl

                  << "b = " << b << endl << "c = " << c << endl << endl;

 

            if ( I == 1) {

                  cout << "Demonstrating b += ++a" << endl;

                  b += ++a;

            }

            else if ( I == 2 ) {

                  cout << "Demonstrating ++a" << endl;

                  ++a;

            }

            else if ( I == 3 ) {

                  cout << "Demonstrating ++a" << endl;

                  ++a;

            }

            else if ( I == 4 ) {

                  cout << "Demonstrating a = a - a" << endl;

                  a = a - a;

            }

            else if ( I == 5 ) {

                  cout << "Demonstrating a = b++ + ++c" << endl;

                  a = b++ + ++c;

            }

            else if ( I == 6 ) {

                  cout << "Demonstrating a *= a" << endl;

                  a *= a;

            }

            else if ( I == 7 ) {

                  cout << "Demonstrating a *= b + c" << endl;

                  a *= b + c;

            }

            else if ( I == 8 ) {

                  cout << "Demonstrating a += ++a + ++b + c++" << endl;

                  a += ++a + ++b + c++;

            }

            else if ( I == 9 ) {

                  cout << "Demonstrating a %= a" << endl;

                  a %= a;

            }

            else if ( I == 10 ) {

                  cout << "Demonstrating a /= a" << endl;

                  if ( a == 0 ) {

                        cout << "Divide by zero. Operation not undertaken. " << endl

                              << "No changes in values of a, b, or c" << endl << endl;

                  }

                  else {

                        a /= a;

                  }

            }

            else

                  cout << "No operation chosen. No changes in the values of a, b, or c" << endl;

 

            cout << "Final values" << endl << "a = " << a << endl

                  << "b = " << b << endl << "c = " << c << endl << endl;

            cout << "Enter 0 to continue, another number to stop: "; cin >> N;

      } while ( N == 0 );

     

      return 0;

}

/*

Use of for repetition structure: calculating compound interest

 

Notes

Using the for structure

 

  The general format for the for is:

 

        for (expression1; expression2; expression3)

            statement

 

  where

      the two semi-colons are always required

     

      expression1 initializes the loop control variable

 

      expression2 is the loop continuation condition; if initially false

      the body of the for is not performed and control goes to the statement

      following the for

 

      expression3 increments (changes) the control variable

 

      the expressions may be comma separated lists of operations that

        evaluate from left to right (the comma has lowest precedence of

        all operators in C++; the value and type of a comma separated

        list is the value and type of the right-most expression of the list;

        comma separated expressions in C++ are used most commonly in for

        statements when several variables must be initialized and incremented

 

      the expressions are optional e.g. expression1 may be omitted if, if e.g.,

        the control variable is initialized elsewhere; if expression2 is omitted

        C++ assumes the continuation is true, creating an infinite loop;

        expression3 may omitted if, e.g., the increment is not needed or

        is calculated in the body of the for

 

      the statement can be a single line statement or a compound statement:

 

        {

            statements

        }

 

  In most cases, the structure has an equivalent while structure

 

        expression1;

        while ( expression2 ) {

            statement

            expression3;

        }

*/

 

// routine

#include <iostream>

#include <iomanip>

#include <cmath>

// alternate #include <math.h>

 

using namespace std;

 

int main()

{

      int years;

      double amount, principal, rate;

 

      cout << "Enter data:" << endl;

 

      cout << setw (35) << "Principal in dollars and cents: ";

      cin >> principal;

 

      cout <<  setw (35) << "Interest as a fraction: ";

      cin >> rate; cout;

 

      cout <<  setw (35) << "Years as a whole number: ";

      cin >> years; cout << endl;

 

      cout << "Output:" << endl;

 

      cout << setw (7 ) << "Year" << setw( 14 )

            << "Amount" << endl;

     

      for ( int year = 0; year <= years; year++ ) {

            amount = principal * pow ( 1.0 + rate, year );

            cout << setw ( 7 ) << year

                  << setiosflags( ios::fixed | ios::showpoint )

                  << setw( 14 ) << setprecision (2)

                  << amount << endl;

      }

 

      cout << endl;

 

      return 0;

}

/*

Assignments and expressions. Assignment and relational operators

 

The form of an assignment and an example of an assignment statement in C++ is:

 

      variable = expression

 

a = 10

 

An expression is formed by combining constants and variables according to rules of combination

 

In C++ an assignment statement itself has a value. The value of an assignment statement is the value that is placed in the left variable

 

It is easy to mistakenly enter ‘=’ where ‘==’ is intended. For example:

 

      if ( x == 10 )

            x = 5;

 

may mistakenly be written:

 

      if ( x = 10 )

            x = 5;

 

There are two cases

      x is initially 10. The value of x == 10 is true; therefore in the first if

      the assignment is executed and x is set to 5

 

      x is initially not 10. In the first if, there is no (re) assignment and

      the value of x is unchanged

 

In the second if statement, the effect of the assignment is, regardless of the initial value, to first assign the value to 10. The assignment statement itself has the value 10 which is taken in C++ to be true (any value other than 0 is ‘true’ while 0 is ‘false’) and therefore x is assigned to 5

 

Arithmentic assignment and increment and decrement operators

 

Since assignment statements have a value a variable can be set equal to an assignment statement. For example

 

      b = (a = 7)

 

first sets a to 7 and then sets b to the value of the assignment which is also 7. Therefore, given the associativity of the assignment operator, the foregoing assignment(s) can be rewritten

 

      b = a = 7

 

Similarly, the following sets all variables to 0:

 

      d = c = b = a = 0

 

Expressions of the form

 

      variable = variable operator expression

 

Can be rewritten

 

      variable operator= expression

 

As examples

 

      c += 3 is equivalent to c = c + 3

      c += a + b is equivalent to c = c + a + b

 

Similarly

 

      c -= 0 is equivalent to c = c – 0

      c *= a + b is equivalent to c = c * ( a + b )

      c /= 5 is equivalent to c = c / 5

      c %= 9 is equivalent to c = c % 9

 

The increment and decrement operators are defined as follows

 

Operator

Name

Sample expression

Explanation

++

preincrement

++variable

Increment the variable by 1, then use the its in the expression in which it resides

++

postincrement

variable++

Use the current value of the variable in the expression in which it resides, then increment it by 1

--

predecrement

--variable

Decrement the variable by 1, then use the its in the expression in which it resides

--

postdecrement

variable--

Use the current value of the variable in the expression in which it resides, then decrement it by 1

 

Examples. In the following a is 4 and b is 5 before the statement is executed:

 

      a++

 

and

 

      ++a

 

both result in the value 5 being assigned to a. In,

 

      b = 10 * (a++)

 

and

 

      b = 10 * (++a)

 

the results are different. In both cases, the the value of a is reassigned as 5. However, in the first, the value assigned to b is 50, whereas in the second it is 40. Since both forms of ++ (pre and post) have precedence over *, the parentheses are unnecessary

 

*/

/*

A routine that demonstrates counter controlled repetition

*/

 

// Class average with counter-controlled repetition

 

#include <iostream>

using namespace std;

 

int main()

{

      int total,

            gradeCounter, // # of grades entered

            grade,

            average;

 

      //initialize

      total = 0;

      gradeCounter = 0;

 

      //process

      while ( gradeCounter < 10 ) {

            cout << "Enter grade: ";

            cin >> grade;

            total = total + grade;

            gradeCounter = gradeCounter + 1;

      }

 

      //output and end

      average = total/10;

      cout << "Class average is " << average << endl;

 

      return 0;

}

/*

A routine that demonstrates sentinel controlled repetition and use of iomanip and static_cast

*/

 

/*

Class average with sentinel controlled repetition

 

Demonstrates use of <iomanip> or <iomanip.h> for parametrized stream manipulators such as setprecision and setiosflags

 

Note that ios::fixed causes a floating-point value to be output in fixed-format (not scientific) notation and ios::showpoint results in the decimal point being

shown even trailing decimal zeros. The bitwise inclusive or operator (|) is used

to separate multiple options in a setiosflags call

 

The cast operator static_cast is used to create a temporary floating-point copy

of the operand 'total' in static_cast < float > (total). This is an explicit

conversion. The C++ compiler does not evaluate expressions which contains

different data types. Therefore in the expression

 

  static_cast< float >(total) / gradeCounter,

 

the int variable is promoted to float; this is an example of a promotion or

implicit conversion operation in which all variables in an expression are

promoted to its highest type (see promotion hierarchy below

*/

 

#include <iostream>

#include <iomanip>

using namespace std;

 

int main()

{

      int total,

            gradeCounter, // number of grades entered

            grade;

      float average;

 

      //initialize

      total = 0; gradeCounter = 0;

 

      //process

      cout << "Enter grade or enter -1 to end: ";

      cin >> grade;

 

      while ( grade != -1 ) {

            total = total + grade;

            gradeCounter = gradeCounter + 1;

            cout << "Enter grade or enter -1 to end: ";

            cin >> grade;

      }

 

      //output and return

      if ( gradeCounter !=0 ) {

            average = static_cast< float >(total) / gradeCounter;

            cout<< endl << "Number of grades entered is " << gradeCounter << endl;

            cout << "Class average is " << setprecision (2)

                  << setiosflags( ios::fixed | ios::showpoint )

                  << average << endl << endl;

      }

      else

            cout << "No grades were entered" << endl << endl;

 

      return 0;

}

/*

Use of switch multiple selection structure

*/

#include <iostream>

using namespace std;

 

int main()

{

      int grade,                    // one grade

            aCount = 0,             // number of A's

            bCount = 0,

            cCount = 0,

            dCount = 0,

            fCount = 0,

            nStudents = 0;

 

      float cum_score = 0.0;        // used to calculate the average grade

     

      cout << "Enter the letter grades." << endl

            << "Enter the EOF character to end input." << endl;

 

      while ( ( grade = cin.get() ) != EOF) {

 

            switch ( grade ) {

 

                  case 'A':

                  case 'a':

                        ++aCount;

                        cum_score = cum_score + 4;

                        nStudents = nStudents + 1;

                        break;

 

                  case 'B':

                  case 'b':

                        ++bCount;

                        cum_score = cum_score + 3;

                        nStudents = nStudents + 1;

                        break;

 

                  case 'C':

                  case 'c':

                        ++cCount;

                        cum_score = cum_score + 2;

                        nStudents = nStudents + 1;

                        break;

 

                  case 'D':

                  case 'd':

                        ++dCount;

                        cum_score = cum_score + 1;

                        nStudents = nStudents + 1;

                        break;

 

                  case 'F':

                  case 'f':

                        ++fCount;

                        nStudents = nStudents + 1;

                        break;

 

                  case '\n': // ignore newlines,

                  case '\t': // tabs,

                  case ' ':  // and spaces in input

                        break;

 

                  default:

                        cout << "Invalid letter. Reenter grade." << endl;

                        break; // optional

            }

      }

 

      cout << "\n\nResults."

            << "\n\n Totals for each letter grade:"

            << "\n  A: " << aCount

            << "\n  B: " << bCount

            << "\n  C: " << cCount

            << "\n  D: " << dCount

            << "\n  F: " << fCount

            << "\n\n The total number of grades is: " << nStudents;

 

      if ( nStudents > 0 ){

            cout << "\n The average grade on a 4.0 scale is: "

                  << cum_score / nStudents << endl << endl;

      }

 

      return 0;

}

/*

Promotion hierarchy for built-in data types

 

Data types

 

long double

 

double

 

float

 

unsigned long int

(synonymous with unsigned long)

long int

(synonymous with long)

unsigned int

(synonymous with unsigned)

int

 

unsigned short int

(synonymous with unsigned short)

short int

(synonymous with short)

unsigned char

 

short

 

char

 

 

*/

 

/*

Header files

 

Standard library leader file

Explanation

Old-style header files

<assert.h>

Contains macros and information for adding diagnostics that aid pro­gram debugging. New version: <cassert>

<ctype.b>

Contains function prototypes for functions that test characters for cer­tain properties, and function prototypes for functions that can be used to convert lowercase letters to uppercase letters and vice versa. New version: <cctype>

<£loat.h>

Contains the floating-point size limits of the system. New version: <cfloat>

<limits.h>

Contains the integral size limits of the system. New version: <climits>

<math.h>

Contains function prototypes for math library functions. New version: <cmath>

<stdio.h>

Contains function prototypes for the standard input/output library functions and information used by them. New version: <cstdio>

<stdlib.h>

Contains function prototypes for conversions of numbers to text, text to numbers, memory allocation, random numbers, and various other utility functions. New version: <cstdlib

<string.h>

Contains function prototypes for C-style string processing functions. New version: <cstring>

<time.h>

Contains function prototypes and types for manipulating the time and date. New version: <ctime>

<iostream.h>

Contains function prototypes for the standard input and standard output functions. New version: <iostream>

<iomanip.h>

Contains function prototypes for the stream manipulators that enable formatting of streams of data. New version: <iomanip>

<fstream.h>

Contains function prototypes for functions that perform input from files on disk and output to files on disk. New version: < fstream >

New-style header files

<utility>

Contains classes and functions that are used by many standard library header files

<vector>, <list>, <deque>, <queue>, <stack>, <map>, <set>, <bitset>

The header files contain classes that implement the standard library containers. Containers are use to store data during a program’s execu­tion… part of the “Standard Template Library”

<£unctional>

Contains classes and functions used by algorithms of the standard library

<memory>

Contains classes and functions used by the standard library to allocate memory to the standard library containers

<iterator>