IV. Introduction to a C++ Program

(parts of chapter 2 and 3)

Warnings:

1. Visual C++ is more than a compiler, it's an Integrated Development Environment, containing many more tools that we'll get to this quarter. Focus only on tools needed now!

2. C++ is VERY powerful and complex language. We will introduce only those portions needed, and not show everything language is capable of right away. But be aware that unintended "mistakes" may be interpreted as a correct feature of the language and thereby cause havoc. Program carefully!

EXAMPLE:

A program to calculate revenue generated by cable installation. Based on a $25.00 per site service charge and $2.00 per foot of cable used in each installation. (Installer measures cable by the yard.)
Data Object Kind of value Type of data Name
Number of installations variableinteger Installations
Yards of cable used variablereal YardsOfCable
Feet of cable used variablereal FeetOfCable
Revenue generated variablereal Revenue
Installation service charge constantreal ServiceCharge
Cost of cable per foot constantreal CostPerFoot

ALGORITHM:

READ Installations, YardsOfCable

FeetOfCable = 3.0 * YardsOfCable

Revenue = Installations * ServiceCharge + CostPerFoot * FeetOfCable

PRINT Revenue

C++ PROGRAM (overhead or computer projected):

(text page 42)

(show execution if possible: shows I/O)

/*----------------------------------------------------
This program calculates the revenue generated by an employee installing coaxial cable.  
Based on installation charge of $25.00 and cost per foot of cable of $2.00.
Program Input(keyboard): The number of installations, The yards of cable installed Program Output (screen): The revenue generated ----------------------------------------------------------------------*/ #include <iostream.h> int main(void) { //PROGRAM CONSTANTS: const double ServiceCharge = 25.00, //service charge per installation CostPerFoot = 2.00; //unit cable cost //PROGRAM VARIABLES: int Installations; //number of installations (input) double YardsOfCable, //yards of cable used (input) FeetOfCable, //feet of cable used (computed) Revenue; //revenue generated (computed) cout <<"\nPlease enter:" <<"\n\tThe number of installations, and" <<"\n\tThe yards of cable used.\n"; cin >> Installations >> YardsOfCable; FeetOfCable = 3.0 * YardsOfCable; Revenue = Installations * ServiceCharge + CostPerFoot * FeetOfCable; cout << "The revenue generated = $" << Revenue << "\n\n"; return 0; }//end of main

***NOTE declarations of all variables at top of program! Book doesn't do this. WE WILL!

-Things To Explain (LOTS!):

(** This is only an introduction to these concepts! Each will be covered in more depth later!)

-Comments: /* ... */ vs. //

- #include (iostream.h needed for i/o - cin/cout)

- "int main(void)" - (functions, "return 0") - all programs need main function

-"void" is the parameter of the function

-don't need to understand it all yet!

- { }

- "const" (syntax error if try to change its value)

- "int" vs. "Double" - lists of variables

- cout, "\n" "\t" << (prints info to i/o stream)

- cin >> (gets info from i/o stream and places into variables)

- purpose of semi-colon: to create a statement ( a C++ program is a series of statements)

KEYWORDS are C++ terms with reserved meaning/function (see App. B)

-those we've seen: main, void, int, const, double, return

IDENTIFIERS are terms "invented" by the programmer to identify specific program objects, such as constants, variables, and functions. Syntax: must begin with a letter, and contain letters, digits and non-consecutive underscores.

***C++ is CASE-SENSITIVE! Keywords are always lower case, else syntax error. Be consistent with identifiers! YardsOfCable is not same as yards_of_cable or yardsofcable!!! It's best to follow the rule in the book: begin with caps, concatenated words are capitalized (YardsOfCable)

EXPRESSIONS - a sequence of one or more data objects and zero or more OPERATORS, that combine to create a value - a semi-colon at the end of an expression creates a STATEMENT , therefore, statements have values! (Usually don't need to be concerned, but sometimes this feature is important -- mostly in future)

Suggest that students type in the program and run it.

Suggest that students write "hello world" program.

Suggest that students examine and understand program in figure 3.2 (radius of sphere)

(Possible "mini-assignments")

**Stress importance of becoming familiar with VC++ environment!!


V. A Closer Look at C++ Programs

(Chapter 3 - expressions, libraries)

LIBRARIES

-Use pre-written libraries to avoid unnecessary work! Many routines already written for various kinds of programs: math, graphics, windows, etc.

-Create your own libraries of commonly used functions in this, and future, courses

-Libraries have two parts:

1.) INTERFACE - contains minimal info on what is in libaray and how to use these items. This is contained in a separate, special file called a HEADER FILE. (File extension: *.h) All users must have access to this file in order to know how to use items in the library.

2.) IMPLEMENTATION - contains the definitions of the items. Contained in another separate file called the IMPLEMENTATION FILE. (File extension *.cpp) Most pre-defined libraries do not allow programmer access, to prevent changing. (If you changed a function to meet your needs, it wouldn't meet the needs of another programmer!)

-Neither of these two parts can stand alone and execute! They don't contain a "main" function.

-Pre-defined libraries are located in a special directory so the compiler knows where to look for them. Programmer-defined libraries can be placed wherever you want, as long as you tell the compiler where to look. (More on this later.)

-In order for a program to use a library, must instruct the compiler to use it, using a COMPILER DIRECTIVE. (CD's begin with # symbol). A #include tells compiler to use the file listed.

-Placing the library name in <>'s tells compiler to look in default include directory.

-When compiler sees #include <something.h>, it gets the specified file, and actually inserts the code into the machine code created. Your program gets bigger! (You won't see it in your source code, tho.)

-Then, when compiler sees objects in your source code that were defined in the library, it knows if you're using that object correctly.

EXAMPLE - see fig. 3.2, pg 77 - radius program, uses math.h library for pow( ) function



DATA TYPES

The fundamental C++ data types:

- Characters: letters, digits, symbols, punctuation - declared as char (uses 8 bits)

-Integers: positive and negative whole numbers - declared as int (machine word -16,32)

-variations: long int (32 bits), short int (16 bits), unsigned long/short int

-Reals: positive and negative numbers w/decimal point - declared as float( 32 bits, seven digit precision), double (64 bits, 15 digit precision), long double (machine dependent: 80,96, 128, 19 digit precision)

(note that this is NOT "float real", "double real", etc)

**REMEMBER that mixing numeric data types in math expressions yields a real value!

-CHARACTER CONSTANTS- a single character value (one ASCII value) which must be enclosed in single quotes: 'A', '5', '$',

-Some ASCII values have no associated (visible) character on keyboard/screen, or they are characters used by C++ language (\, quotes, etc) These are represented using ESCAPE SEQUENCES. Some most used:

'\n' newline (contrast at beginning/end of output. Look at sequential appearances.)

'\t' tab

'\f' formfeed

'\\' to print \

'\'' to print single quote

'\" ' to print double quote

'\?' to print ?

CHARACTER STRING CONSTANTS- multiple character values treated as a whole (a string), which must be enclosed in double quotes: "This is a string.", "Go to next line.\n", "The teacher said, \"C++ is FUN!\" "

NUMERIC EXPRESSIONS

-Math operators, as learned in pseudocode: +, -, *, /, %

-Mixing numeric types in an expression always yields a real value (this actually expands the integer value into a real value to do computation: PROMOTION)

-Modulus operator, %, requires integer operands, else syntax error

-Order of precedence is as learned in pseudocode

BUILT-IN FUNCTIONS

-Libraries contain many functions we can use

-Typical math functions: abs(x), pow(x,y)

-These return a value which can be used as appropriate

EXPLICIT TYPE CONVERSION (TYPE CASTING)

-To change a value into a different data type, eg:

double( j ) - creates a 64bit real value from j's value

int(x) - creates integer value from x's value (truncates)

(functional notation)

-sometimes written: (int) x or (double) j

(cast notation)

ASSIGNMENT EXPRESSIONS

-To place a value into a variable data object

-Assignment operator: =

-data object must be on left of =

-These are not the same: A=B; B=A;

-Show what happens with: A = A + 1;

-Show swap algorithm:

temp = a;

a = b;

b = temp;

-Assignment shortcuts:

CHAINING ASSIGNMENT:

x = 2.0;

y = x;

-can be written: y = x = 2.0;

-eg, initialize counters to 0: a = b = c = d = 0;

INCREMENT/DECREMENT OPERATORS

-quicker way to add/subtract one to data object:

x = x + 1; --> x++;

x = x - 1; --> x--;

-can use prefix notation: ++x;

-but when used in larger expression, could have surprising results!!

-Remember that expressions produce values, and the value produced by x++ is just x (even tho x is still changed!), and the value produced by the expression ++x is (x+1), so that:

x = 1;

y = x++;

assigns 1 into x, AND 1 into y, and THEN puts 2 into x, but

x = 1;

y = ++x;

assigns 1 into x, and then puts 2 into x, and THEN puts 2 into y.

-The moral of the story: BE CAREFUL!!! AVOID USING ++, -- OPERATORS WITHIN A LARGER EXPRESSION, UNTIL YOU'RE MORE ADVANCED!

COMBINING ASSIGNMENT & MATH OPERATORS:

-The statement:

y = y @ 3;

can be written:

y@= 3;

where @ is any math operator.

-Just a shortcut - don't overdo! Can get confusing!

INPUT/OUTPUT STATEMENTS

-keyboard input characters are placed in the INPUT STREAM, called istream, which transmits the characters from the computer's op sys into the program.

-screen output characters are placed in the OUTPUT STREAM, called ostream, which transmits the characters from the program to the computer system

-istream and ostream are not keywords of C++: they are examples of pre-defined classes, which reside in the iostream.h library. (Our first example of having to use classes without knowing their implementation, but only how to use them.)

-There are two important objects defined in iostream.h which we will use:

cin - handles keyboard input

cout - handles screen output

-As seen, an input statement has the form of:

cin >> variable;

or

cin >> variable1 >> variable2 >> ... >> variableN;

(this statement operates from left to right)

-">>" is the INPUT OPERATOR (or extraction operator, because it extracts data from stream)

-Program execution is suspended until user enters required number of values

-As seen, and output statement has the form of:

cout << expression;

or

cout << expression1 << expression2 << ... << expressionN;

where expression is a data object (variable, numeric constant, string constant, etc)

-OUTPUT FORMATTING determines the appearance of output values

-important to learn, to create professional-appearing output (ie, two decimal places for dollar amounts, lining up columns or tables, spacing between values imbedded in sentence, etc)

-C++ provides pre-defined FORMAT MANIPULATORS in iomanip.h

-use format manipulators within any cout statements to control appearance

-Factors (some) we can control:

Field width - default is 1 - will overflow as needed - useful for aligning columns/tables

-to use, insert the f.m. "setw(width)" in front of every object to apply to

-eg:

cout << setw(10) << num1 << setw(10) << num2;

Precision (number of places after decimal) - default is 6

-to use, insert the f.m. "setprecision(precision)" at beginning of cout statement

(only need to use once, unless you want different precisions in same statement):

-eg:

cout << setprecision(3) << num1;

cout << setprecision(4) << "The answer is " << Answer;

Show decimal point - default won't!

- to use, insert the f.m. "setiosflags(flaglist)" and a flag of "ios::showpoint"

-eg:

cout << setiosflags(ios::showpoint) << setprecision(3)

<< Answer;

-usually used with another flag, ios::fixedpoint, else will be floating:

-eg:

cout << setiosflags(ios::showpoint | ios::fxed)

<< setprecision(3) << Answer;

-these only need to be set once per statement, for all values

Left/right justify - default is right

- to use, insert "setiosflags(flaglist)", with a flag of "ios::left" or "ios::right"

-eg:

cout << setiosflags(ios::showpoint | ios::fxed | ios::left)

<< setprecision(3) << Answer;

-need only be set once per statement, will affect all values

-Can combine ALL format manipulators, as needed

-eg:

cout << setiosflags(ios::showpoint | ios::fxed)

<< setprecision(3) << setw(10) << Answer;

-Note use of " | " (pipe) character to divide flag list

-Summation of output formatting:

-Three format manipulators:

setw(width) - to specify a field with (defalt is 1)

- must insert before each value to format

setprecision(p) - to specify number of places after decimal

(default is 6)

-set once per cout statement

setiosflags(flaglist) - with these flags:

ios::showpoint - to force decimal point to appear

(default is no point)

ios::fixed - to display number in fixed point format

(default is floating point, mostly safe)

ios::left - to display value left justified in field

(default is right)

-set once per statement

NOTE that the flags showpoint, fixed, left, etc, are part of the pre-defined class ios

- "::" is the scope operator which lets us use these flags

-another example of using something already created for us, which we don't really know how they work, but we can still use them, because we know what they do and how to use them

EXAMPLES (formatting):

-Suppose a = 42, b = 3.145, c = 3.0

-Show output of the following:

cout << a << b << c;
423.1453

cout << setw(10) << a << b << c;
        423.1453

cout << setw(10) << a << setw(10) << b << setw(10) << c;
        42     3.145         3

cout << setprecision(3) 
     << setiosflags(ios::showpoint | ios::fixed)
     << setw(10) << a << setw(10) << b
     << setw(10) << c;
        42     3.145     3.000

cout << setprecision(2)
     << setiosflags(ios::showpoint | ios::fixed)
     << setw(10) << a << setw(10) << b
     << setw(10) << c;
        42      3.15      3.00           **rounds!

cout << setprecision(5)
     << setiosflags(ios::showpoint | ios::fixed)
     << setw(10) << a << setw(10) << b
     << setw(10) << c;
     42   3.14500   3.00000

cout << setprecision(2)
     << setiosflags(ios::showpoint)  //no fixed!
     << setw(10) << a << setw(10) << b
     << setw(10) << c;
        42      3.15      3.00

cout << setprecision(2)
    << setiosflags(ios::showpoint | ios::fixed | ios::left)
    << setw(10) << a << setw(10) << b
    << setw(10) << c;
42        3.15      3.00

-Suggest students do practice exercises at end of section 3.6