160
PART 1 Language Overview Introduction and justification. Turbo C++ development environment. Tutorial examples of C++ programs. Basic language philo sophy. Examples of variables, constants, character processing, arithmetic, functions, and control structures. Input/Output basics in C++

PART 1 Language Overview - courseweb.stthomas.educourseweb.stthomas.edu/tpsturm/private/notes/cplusplus/cp2chap1.pdf · • Provides support for object-oriented design and programming

  • Upload
    buimien

  • View
    219

  • Download
    0

Embed Size (px)

Citation preview

PART 1

Language Overview

• Introduction and justification.

• Turbo C++ development environment.

• Tutorial examples of C++ programs.

• Basic language philosophy.

• Examples of variables, constants, character processing, arithmetic, functions, and control structures.

• Input/Output basics in C++

Part 1, Page 2 C++ Programming

Language Overview Part 1, Page 3

INTRODUCTION TO C++

• Designed and developed by Bjarne Stroustrup at AT&T Bell Labs in the early 1980's

• Initially released in late 1985 - by mid-1986 already had 24 systems with commercial ports of C++, version 1.0

• Intended to be an add-on pre-processor for a conventional C compiler - Improve and extend C - 1988 saw the first native C++ compilers

• The original C++ language reference is: The C++ Programming Language by Bjarne Stroustrup - 1986. It applied to AT&T versions 1.0, 1.1, and 1.2.

• As the language evolved, the C++ language references were: The Annotated C++ Reference Manual by M. A. Ellis and Bjarne Stroustrup - 1990. for versions 2.0 and 2.1, and The C++ Programming Language 2nd edition by Bjarne Stroustrup - 1991 for version 3.0

• The ANSI standards committee for C++ (X3J16) started on the standardization process in December, 1989, and adopted a joint ANSI/ISO standard for C++ in January 1998.

• A few older C++ compilers are only compliant with version 1.2. Most are up to version 2.0 (Turbo C++ 1.01/Borland C++ 2.0, for example), some are up to version 2.1 (Turbo C++ 2.0/Borland C++ 3.0, Green Hills C++, Oregon C++, for example), Turbo C++/Borland C++ 3.1 are up to version 3.0, Borland C++ 4.0 implements many ANSI features. Borland C++ 4.5, Turbo C++ 4.5 implement the current ANSI standard.

Part 1, Page 4 C++ Programming

Table of Compiler Versions vs. C++ Versions

AT&T C++ Version

Compiler 1.0 1.1 1.2 2.0 2.1 3.0 ANSI

Borland C++ 2.0 3.0 3.1 4.5

Green Hills C++ 1.0

LPI C++ 3.0

Microsoft C/C++ 7.0

Visual C++ 1.0,1.5

MPW C++ 3.3

Oregon C++ 2.0.1 2.1

Symatec C++ 6.1

Turbo C++ 1.0 1.01 2.0,3.0 3.1

Watcom C/C++ 3.0 4.0

Zortec C++ 1.0 2.0 3.0

Language Overview Part 1, Page 5

WHY IS C++ POPULAR ?

• Provides a fairly complete set of facilities for dealing with a wide variety of applications.

All the useful data types, including pointers and strings.

A rich set of operators and control structures.

A powerful and flexible I/O class library

• Is a small language with built-in data types and operators that are closely related to most assemblers. There need only be a small "semantic gap" between C++ and the computer hardware.

• A growing number of C++ programs and C++ programmers.

• With care and thought, C++ programs can be made portable.

• Compilers are available for a wide variety of machines, from micros to mainframes.

• Useful as an assembler replacement, increasing software quality and programmer productivity, thus retaining the low-level strengths of C

• Provides support for creating and using data abstractions

• Provides support for object-oriented design and programming

• Provides improvements for certain C constructs, and for input/output

• Takes almost nothing away from C, while adding enormous capability

• Retains and improves organization capabilities of C

Part 1, Page 6 C++ Programming

DISADVANTAGES OF C++

• Can write cryptic and "unreadable" programs.

• Operands and functions can have "side effects."

• Not a "beginner's" language.

• Discipline is left to programmers.

• If it was easy to "shoot yourself in the foot" with C, then C++ straps a loaded uzi to your leg

• "Like walking blindfolded through an Indiana Jones adventure" - Ladd

• C++ assumes you know exactly what you are doing - almost anything is legal in some sense - compiler/preprocessor just follows directions

• Need substantial programming experience before venturing into C++

• Can migrate a C program forward to C++, but virtually impossible to migrate a C++ program back to C

Language Overview Part 1, Page 7

CHARACTERISTICS OF C++

• Has built-in data types, but not strongly typed like Pascal, more strongly typed than C

• Has high level for support of objects, but ultimately requires specification at a C programming level, which is just slightly lower than FORTRAN, Basic, COBOL, or Pascal

• A medium sized language, has a fixed set of operator tokens, does not have exponentiation, does not have input/output statements, does not have complex numbers built in, does not have logical variables built in

• General purpose, but optimized for system programming

• Portable, but most compatible with UNIX

• Remarkably standard - because of mentors

• Object oriented - can define objects, and the operators and functions to process them

• Supports structured programming - can write most user-specific code at a high level, while still maintaining low-level control in the called functions

• Supports data abstraction - allows designers to think about the types of operations they would like to provide for a data item, rather than the statements that the programming language supports

Part 1, Page 8 C++ Programming

hello.cpp /* HELLO.CPP: First C++ program - after KR, page 6 */ #include <iostream.h> main() { cout << "hello, world\n"; return 0; }

Language Overview Part 1, Page 9

hello.cpp EXPLANATION

• All C++ programs consist of one or more files containing one or more "functions" each.

• One form of comments are begun with /* and ended with */. Comments may appear anywhere white space is allowed and should be used freely. Comments of this form may not be nested.

• An include statement must be used whenever any library function, any class in the class libraries, or any object defined in the class libraries (in this case cout) is used.

• All C++ programs must contain a function named main, which is where the program begins execution.

• In general, main will call other functions. Some are system-supplied library functions for mathematics, input/output, and system interaction. Others are written by the programmer.

• Braces { } enclose the statement(s) that make up the function. They are also used to group a set of statements into a single statement where a single statement is required. (In other words, C++ is a block-structured language.)

• A function is invoked by using its name. There is no CALL statement as there is in some other programming languages.

• The C library of input/output functions is included for compatibility in C++, but C++ provides its own set of input/output functions. These can only be intermixed with care. (See the input/output section.)

• The string "hello, world\n" is a string constant containing 13 characters - the \n represents a single character, a “newline” character which is a line feed or a carriage return or both in either order, depending upon what the system prefers.

• Statements are terminated by a ;

Part 1, Page 10 C++ Programming

Editing Within Various Operating Systems

UNIX

vi hello.cpp

VMS

edit hello.cxx

Turbo C++

tc Alt-F O hello.cpp

Borland C++

bc Alt-F O hello.cpp

Language Overview Part 1, Page 11

CREATING A C++ PROGRAM

• A "typical" C++ source program consists of one or more user created files. These files usually have a .cpp file extension (or .cxx for VAX/VMS). Each of the files contains one or more user-defined C++ functions. These files are created using a separate or integrated text editor.

• In addition to the .cpp files, longer and more complex programs also contain one or more user created header files. These files usually have a .h file extension (or .hpp or .hxx on some systems).

• In one of the (or the only) source files there is exactly one function called main. The function main is the entry point into the C++ program. The function main calls the other user defined functions in order to accomplish the intended task of the C++ program.

• There are no input/output statements in the C++ language. Instead, use is made of the built-in I/O class library. For example, function calls can be made to the I/O functions in the C++ class library. In our first program, the << operator was “overloaded” to provide “stream output”. (C++ provides for much more input/output control than C.)

Part 1, Page 12 C++ Programming

Compiling and Running Programs in Various Operating Systems

UNIX

cpp hello.cpp a.out

VMS

cxx hello link hello run hello

Turbo C++, Borland C++ (Command Line)

tcc hello hello

Turbo C++, Borland C++ (Integrated Development Environment)

Cntr-F9

Language Overview Part 1, Page 13

COMPILING AND RUNNING A C++ PROGRAM

The following steps are required to compile, link, and run a C++ program:

1. Compile the program. The compiler will:

a. Preprocess each xxx.cpp file

(some systems use a .cxx file extension)

- define constants

- expand macros

- include .h files (especially function and class declarations)

(some systems use .hpp or .hxx file extensions)

- conditionally retain source code

b. Translate C++ source code into relocatable binary machine code (object files)

- named xxx.o (UNIX) or xxx.obj

- each file can be compiled separately

2. Link the program. The linker will:

a. Obtain all specified object files from various compiles

b. Obtain all necessary precompiled library functions

c. Produce an executable file named a.out (UNIX default) or xxx.exe

d. (UNIX only) Perform cleanup by deleting xxx.o

3. Run the program.

Place the program into execution

Part 1, Page 14 C++ Programming

SPECIAL CONSIDERATIONS

• In the UNIX, Turbo C++ command line, and Borland C++ command line compilers, the cpp, tcc, or bcc command both compiles and links

• In VMS the logical name LNK$LIBRARY may need to be defined as SYS$LIBRARY:VAXCRTL each time the user logs on, so as to obtain the VAX C Run-time Library during the linking phase This is most efficiently done by adding the following line to the login.com file:

define lnk$library sys$library:vaxcrtl

• In Turbo C++ and Borland C++, the Control-F9 key compiles, links, and places the program into execution. (Alt-F9 to compile only, F9 to compile if needed and link only, Ctrl-F9 to compile if needed, link if needed and run)

• In Turbo C++ and Borland C++ 4.0 and later for Windows, you must first configure the development environment to generate a terminal-style text interaction using a DOS window. This is done with the Target Expert. - select the window containing the source code - hold down the RIGHT mouse button - select target expert - select the EASY-WIN target type

• In all Borland products there is a built-in make facility that determines (based on file date/time stamps) whether a program needs to be re-linked or re-compiled and re-linked before execution.

Language Overview Part 1, Page 15

Editing Within the Borland C++ 4.0 for Windows System

win Alt-W followed by number of Borland C++ Version 4.0 group Return

(or double click on Borland C++ Version 4.0 group icon)

Return (or use arrow keys until Borland C++ 4.0 icon highlighted and press return)

(or double click on Borland C++ 4.0 icon) Alt-F O c:\bc4\cppart1\hello.c

Part 1, Page 16 C++ Programming

USE OF BORLAND C++ 4.0 for WINDOWS INTEGRATED DEVELOPMENT ENVIRONMENT

1. Turn on the IBM PS/2.

2. Start up Microsoft windows: win

3. Open up the Borland C++ Version 4.0 program group:

double click on Borland C++ Version 4.0 group icon

4. Launch the Borland C++ Version 4.0 integrated development environment:

double click on Borland C++ 4.0 icon

5. You may need to get past an initial startup screen with a: (carriage return)

6. Get into the load file popup by pressing: Alt-F

or double click on File in menu bar

7. Specify the name of the new file you are about to create or the old file you are about to modify

8. Edit the file.

9. Press Alt-F10 or the right mouse button to activate the speed menu

9. a. From the speed menu select target expert

9. b. From the target type menu select EasyWin

9. c. Select OK or press return to return to the editor

10. Press Alt-F9 to compile and view compiler error messages.

either 11. a. Press F9 to link and view linker error messages.

or 11. b. Press Control-F9 to link and run program in debugger.

12. A DOS window will appear with a terminal interaction screen.

12. a. After viewing results, close the DOS window to return back to the integrated development environment.

Language Overview Part 1, Page 17

Borland C++ for Windows Main Menu Screen

Part 1, Page 18 C++ Programming

BORLAND C++ 4.0 for WINDOWS MAIN MENU

When the main menu is highlighted, pressing the first key of the menu item name selects that menu item as follows:

F file file selection, open, print, save, ... E edit cut, undo, clipboard ... S search text search, browsing, error search, ... V view breakpoints, watches, global variables, ... P project project file add, delete, view, ... D debug run program, debug display, set, change, ... T tool customizable development tools O options set defaults for IDE, compiler, linker, ... W window window open, arrange, list, ... H help view on-line help

Whether in the main menu or not, pressing Alt-F, Alt-E, Alt-S, Alt-V, Alt-P, Alt-D, Alt-T, Alt-O, Alt-W, and Alt-H select the above menu items, respectively.

The meaning of the function keys, named keys, and key combinations with ctrl and alt, in general, depends on where you are within the Borland C++ system. However, some keys and key combinations have a fixed definition throughout the Borland C++ system. These system keys are listed on the following page.

There is a (customizable) speed bar below the main menu that provides context-sensitive icons. The speed bar is best accessed via the mouse. Positioning the mouse over an icon causes a description of the icon function to appear at the bottom of the screen.

There is also a context-sensitive speed menu that can be brought up either by pressing the RIGHT mouse button or by pressing ALT-F10. This menu occasionally is the only method of access to some control functions.

Language Overview Part 1, Page 19

Borland C++ 4.0 for Windows System Keystroke Mapping (Default)

F1 Display context-sensitive Help F3 Search forward to next string pattern F4 Run to Cursor F5 Debug|Add Breakpoint F7 Debug|Trace Into function calls F8 Debug|Step Over function calls F9 Project|Build All Shift+F4 Window|Tile Horizontal (nonoverlapping) Shift+F5 Window|Cascade (overlapping) Alt+F4 Exits Borland C++ 4.0 for Windows Alt+F5 Debug|Inspector Alt+F7 Search|Previous Message Alt+F8 Search|Next Message Alt+F9 Project|Compile source files in project Alt+F10 Displays a Speed Menu Ctrl+F1 Help|Keyword Search Ctrl+F2 Debug|Program Terminate Ctrl+F3 View|Call Stack Ctrl+F4 Close current window Ctrl+F5 Debug|Add Watch Ctrl+F6 Switch to next window Ctrl+F7 Debug|Evaluate/Modify Ctrl+F9 Debug|Run Ctrl+Shift+P playback a key macro Ctrl+Shift+R record a key macro Ctrl+K+D accesses the menu bar Ctrl+K+S File|Save

Part 1, Page 20 C++ Programming

Borland C++ 4.0 for Windows Editor Commands (Control characters - Default Mapping)

Insert tab character ^I Insert a new line ^N Control character prefix ^P Search for next occurrence ^S Delete word right ^T Delete line ^Y Scroll up one screen ^Z Mark block begin ^K B Copy block ^K C Hide/display block ^K H Indent block ^K I Mark block end ^K K Print block ^K P Quit edit, no save ^K Q Read block from disk ^K R Save and edit ^K S Mark single word ^K T Unindent block ^K U Move block ^K V Write block to disk ^K W Delete block ^K Y Set place marker ^K n Find and replace ^Q A Beginning of block ^Q B End of file ^Q C End of line ^Q D Top of window ^Q E Find ^Q F End of block ^Q K Restore line ^Q L Last cursor position ^Q P Top of file ^Q R Beginning of line ^Q S Restore error message ^Q W Bottom of window ^Q X Delete to end of line ^Q Y Find place marker ^Q n Match pair ^Q [

Language Overview Part 1, Page 21

Borland C++ 4.0 for Windows Editor Commands (Special, Function and Arrow Keys - Default Mapping)

Page up Page Up Page down Page Down moves to the end of a line End moves to the start of a line Home inserts a carriage return Enter turns insert mode on/off Ins Delete character left of cursor backspace deletes the character to the right of the cursor

Del

inserts a tab Tab inserts a blank space Space Edit|Search Again F3 Go to menu bar F10 Character left Back arrow Character right Forward arrow Line up Up arrow Line down Down arrow Moves one word left Ctrl+Left Arrow Moves one word right Ctrl+Right Arrow Selects the character to the left of the cursor

Shift+Left Arrow

Selects the character to the right of the cursor

Shift+Right Arrow

Moves the cursor up one line and selects from the left of the starting cursor position

Shift+Up Arrow

Moves the cursor down one line and selects from the right of the starting cursor position

Shift+Down Arrow

Selects the word to the left of the cursor

Ctrl+Shift+Left Arrow

Selects the word to the right of the cursor

Ctrl+Shift+Right Arrow

Part 1, Page 22 C++ Programming

Borland C++ 4.0 for Windows Editor Commands (Special Key Combinations - Default Mapping)

indent block Ctrl+Shift+I outdent block Ctrl+Shift+U deletes to the end of a line Ctrl+Shift+Y sets bookmark n (0 to 9) Shift+Ctrl+n go to bookmark n (0 to 9) Ctrl+n finds the matching delimiter (forward) Alt+[ finds the matching delimiter (backward) Alt+] inserts a tab character Ctrl+Tab deletes the word to the right of the cursor Ctrl+Backspace moves to the top of a file Ctrl+Home moves to the end of a file Ctrl+End deletes a currently selected block Ctrl+Del inserts a blank space Ctrl+Space moves to the bottom of a screen Ctrl+PgDn moves to the top of a screen Ctrl+PgUp deletes the character to the left of the cursor

Shift+Tab

deletes the character to the left of the cursor

Shift+Backspace

moves the cursor up one screen and selects from the left of the starting cursor position

Shift+PgUp

moves the cursor down one line and selects from the right of the starting cursor position

Shift+PgDn

selects from the cursor position to the end of the current line

Shift+End

selects from the cursor position to the start of the current line

Shift+Home

inserts a blank space Shift+Space inserts a new line with a carriage return Shift+Enter selects from the cursor position to the start of the current file

Ctrl+Shift+Home

selects from the cursor position to the end of the current file

Ctrl+Shift+End

selects from the cursor position to the bottom of the screen

Ctrl+Shift+PgDn

selects from the cursor position to the top of the screen

Ctrl+Shift+PgUp

Edit|Undo Alt+Backspace Edit|Redo Alt+Shift+

Backspace

Language Overview Part 1, Page 23

Compiling, Linking, and Running Programs in Borland C++ 4.0 for Windows

Alt-F10 Access speed menu X Select target expert (down arrow) (down arrow) (return)

Select EasyWin target type

Alt-F9 Compile Cntr-F9 Link and Run (compile if necessary)

Part 1, Page 24 C++ Programming

Learning the Development Environment

See Appropriate Appendix

Language Overview Part 1, Page 25

LAB 1 for Part 1

1. Turn on the terminal or PC

2. Get into the appropriate package or machine

3. Invoke the editor to create the file hello.cpp

4. Compile and execute hello.cpp

5. Modify hello.cpp to say something besides "hello, world."

6. Compile and execute hello.cpp again

7. Locate and examine the programs hello2.cpp, hello3.cpp, hello4.cpp, and fc1.cpp, already stored on disk - for IBM PC systems, the file hello2.cpp is usually located in one of the following directories, depending on the version of the compiler being used: C:\TC\CPPPROGS\HELLO2.CPP C:\BC4\CPPPROGS\HELLO2.CPP C:\BC45\CPPPROGS\HELLO2.CPP C:\TCWIN\CPPPROGS\HELLO2.CPP - for VAX/VMS systems, the file hello2.cpp is usually located in the group library for the course. For example, for QMCS 280 for fall, 1998, for section 01, the file will be located: USR_GRPLIB:[QMCS280_01_98F.CPPPROGS]HELLO2.CPP

Part 1, Page 26 C++ Programming

hello2.cpp // HELLO2.CPP: hello world program #include <iostream.h> // declarations of stream I/O // some compilers want <stream.hpp> // or <stream.h> instead main() { cout << "Hello C++ world" << endl; return 0; }

Language Overview Part 1, Page 27

hello2.cpp EXPLANATION

• Comments

- C++ supports a second type of comment, the in-line (end-of-line) comment, which is begun with // and ends with the statement newline

• Header File

- The appropriate header file for input/output needs to be included to use cout and cin:

- <stream.hpp> for Zortec C++ version 1.0 and 2.0

- <stream.h> for C++ version 1.2 and earlier

- <iostream.h> for C++ version 2.0 and later

(<iostream.hpp> or <iostream.hxx>

on some systems)

• Output using “insertion operator”

- The << operator is used for sending output to the cout object. cout is an object of class ostream defined in the header file. The << operator is the “left shift” operator from C. However, when used with an ostream object, it is “overloaded” to mean “insert into output” and is commonly called the “insertion operator”

- endl is a stream manipulator defined in the header file. It sends a newline character (or whatever is appropriate, like the \n) to the output stream and does a stream flush.

Part 1, Page 28 C++ Programming

hello3.cpp // HELLO3.CPP: our first C++ program modified #include <iostream.h> main() { cout << "Hello C++" << " world\n"; return 0; }

Language Overview Part 1, Page 29

hello3.cpp EXPLANATION

• Except for long comments at the beginning of files, comments are best written with the // at their beginning (terminated by end of line). This allows blocks of code to be commented out with the /* and */ construct. (/* and */ cannot be nested.)

• By including the header file iostream.h, we obtain declarations and definitions of the ios, istream, ostream, iostream, and streambuf classes; the standard streams cin, cout, cerr, and clog, and the insertion (put, <<) and extraction (get from, >>) operators.

• Output is performed with the << (insertion or put) operator. This syntax makes it easy to "overload" the insertion operator for user-defined classes, allowing customized I/O routines based on "data type".

• hello3.cpp shows that several pieces of output can be concatenated "on the fly". The insertion operator inserts on the right, so the output stream reads the same way we read it on the program line.

• The return 0 statement is only required by very picky compilers that insist we return a value of the proper data type (integer) to _main.

Part 1, Page 30 C++ Programming

fc1.cpp /* FC1.CPP: First version of Fahrenheit-Celsius */ /* Print Fahrenheit-Celsius table for fahr = 0, 20, ... , 300 */ /* From KR, page 9 */ #include <iostream.h> main() { int fahr, // Fahrenheit temperature celsius; // celsius temperature int lower, // lower limit of temp. table upper, // upper limit step; // step size lower = 0; // start at 0 degrees ... upper = 300; // ... go up to 300 degrees ... step = 20; // ... by 20 degrees fahr = lower; while( fahr <= upper ) { celsius = 5 * (fahr-32) / 9; // int arith. cout << fahr << "\t" << celsius << endl; fahr = fahr + step; } return 0; }

Language Overview Part 1, Page 31

fc1.cpp EXPLANATION

• ALL variables must be defined before use, usually at the beginning of the function before any executable statements.

• A definition consists of a "type" or (the name of the class) and a list of variables (or objects) which have that type. The built-in types are:

bool - Boolean (logical) short int - short integer int - standard size integer long int - long integer float - single precision floating point double - double precision floating point long double - extended double precision floating point char - character (a single byte) void - an empty set of values enum - allows arbitrary sets of identifiers to be

used as values

In addition, types char, short int, int, long int may be declared signed or unsigned. short int, int, long int are signed by default, so signed int is the same as int.

• The first executable statements in the function are assignment statements that provide initial values to the variables lower, upper, and step. (Not all variables in C++ are initialized by default — and relying on a default setting by the compiler is considered bad programming practice.)

• The while statement is one of several forms of looping. It repeatedly executes a single statement or a group of statements enclosed in braces as long as the condition in parentheses is true. (If the condition is false to start with, the statement(s) are not executed even once.)

• For readability, the statements within the loop have been indented (with tabs). Since C++ is free-form, this is not a requirement, but the intent is to be able to make the code very readable.

Part 1, Page 32 C++ Programming

• The code on the following page generates the same results, but is totally unreadable.

Language Overview Part 1, Page 33

unreadab.cpp /* Unreadable version of Fahrenheit-Celsius KR, page 9 */ #include <iostream.h> main(){int fahr,celsius,lower,upper,step;lower=0;upper=300 ;step=20;fahr=lower;while(fahr<=upper){celsius=5*(fahr-32) /9;cout<<fahr<<"\t"<<celsius<<endl;fahr=fahr+step;}return 0;}

Part 1, Page 34 C++ Programming

fc1.cpp EXPLANATION (Cont.)

• The statement celsius = 5 * (fahr - 32) / 9; is an assignment statement

• In this example, integer arithmetic is being performed, and the division is truncating

• Re-writing the statement as celsius = (5 / 9) * (fahr - 32); would NOT work because 5/9 would be interpreted as integer

arithmetic (which truncates), thus giving us 0.

• The line sending information to the output stream is a bit more complex than in the previous examples. Note that integer variables (fahr, celsius) are intermixed with a string constant (“\t”) and a manipulator (endl). The insertion operator is “polymorphic,” i.e. it responds to each object in a manner “appropriate” for the object. - For an integer variable object, the value stored in the variable is printed as a whole number using as much width as necessary, but placing no white space either before or after the value. - For a string constant object, the string is printed out literally, after any “escape sequences” (sequences of 2 or more characters starting with the \) are translated into a single character (in this case \t is translated into the horizontal tab character). - For a stream manipulator, the appropriate stream manipulation is performed.

Language Overview Part 1, Page 35

Results of executing fc1.cpp 0 -17 20 -6 40 4 60 15 80 26 100 37 120 48 140 60 160 71 180 82 200 93 220 104 240 115 260 126 280 137 300 148

Part 1, Page 36 C++ Programming

fc1.cpp FORMAT EXPLANATION

• The \t specifies a tab between the two values printed. Note that this results in both numeric columns being left aligned, which is generally undesirable for numbers.

• More advanced forms of output control can be handled by controlling the “state” of the output stream. The state can control such things as: - the width of the field used for output - the justification used within the field - the base used to represent the number - the fill character for padding a field - the number of decimal places - whether a floating point value is forced into a fixed decimal representation or a scientific notation representation

• More details about output formatting are presented in the section on input and output.

Language Overview Part 1, Page 37

fc2.cpp

Part 1, Page 38 C++ Programming

/* FC2.CPP: Print Fahrenheit-Celsius table

Language Overview Part 1, Page 39

Part 1, Page 40 C++ Programming

for f = 0, 20, ... , 300; floating-point version */

Language Overview Part 1, Page 41

Part 1, Page 42 C++ Programming

/* Second version of Fahrenheit-Celsius KR, page 12 */ #include <iostream.h> #include <iomanip.h> main() { float fahr, // Fahrenheit temperature celsius; // celsium temperature int lower, // lower limit of temp. table upper, // upper limit step; // step size lower = 0; // start at 0 degrees ... upper = 300; // ... up to 300 degrees ... step = 20; // ... in 20 degree steps fahr = lower; cout.setf(ios::fixed); while( fahr <= upper ) { celsius = (5.0/9.0) * (fahr-32.0); // double! cout << setprecision(0) << setw(3) << fahr <<" " << setprecision(1) << setw(6) << celsius <<endl; fahr = fahr + step; } return 0; }

Language Overview Part 1, Page 43

fc2.cpp EXPLANATION

• The assignment fahr = lower; and the test while( fahr <= upper ) both contain "mixed mode," yet both work as expected. The int is

converted to float before the operation is done. (Actually, the use of integer variables for lower, upper, and step is rather poor programming practice. C++ has no restrictions on whether integers or real variables control loops. Converting from integer to floating point explicitly at each variable use is tedious and relying on the person reading the code to correctly interpret the mixed mode conventions is risky.)

• 5/9 would give us 0, because 5/9 would be interpreted as integer arithmetic (which truncates). The 32.0 could have been written at 32, but that is poor style since we intend all along to do a floating point operation with floating point operands.

• The statement cout.setf(ios::fixed); changes the state of the cout object (which is an ostream) to do all floating point output in fixed decimal.

• The header file iomanip.h is included to provide more complex control over the output. In particular it allows the setprecision() manipulator specify the number of decimal places printed in fixed decimal, and it allows the setw() manipulator specify the width of the next field output.

• In this example, a floating point number (single, double, or extended precision) is to be printed in a space at least 3 characters wide, with 0 digits after the decimal point. Since fahr is the object following the specification, it will use this format. Next, a floating point number will occupy at least 6 spaces with 1 digit after the decimal point (plus the decimal point itself). The object celsius will be output using these specifications.

Part 1, Page 44 C++ Programming

fc2.cpp OUTPUT 0 -17.8 20 -6.7 40 4.4 60 15.6 80 26.7 100 37.8 120 48.9 140 60.0 160 71.1 180 82.2 200 93.3 220 104.4 240 115.6 260 126.7 280 137.8 300 148.9

Language Overview Part 1, Page 45

fc2.cpp OUTPUT EXPLANATION

• Note that the columns are now aligned on the right. (This is the default alignment when a column width is specified.)

• Note that most stream states are “sticky” - i.e. they keep their values from one output to the next. Thus, if we wanted all of the output to contain one digit after the decimal point, we would only need to specify setprecision(1) once.

The one stream state that is NOT sticky is the field width set by the setw() manipulator. The width is only in effect for the next field output. Thus, if we wanted all of the output to be put into fields 12 characters wide, it would still be necessary to specify setw(12) before both the output of fahr and the output of celsius.

Part 1, Page 46 C++ Programming

Reserved Names in C++ and and_eq asm auto bitand bitor bool break case catch cdecl † char class compl const const_cast continue default delete do double

dynamic _cast

else entry † enum explicit export extern false far † float for fortran † friend goto handle † huge † if inline int interrupt † long

mutable namespace near † new noalias † not not_eq operator or or_eq overload † pascal † private protected public register reinterpre

t_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 xor xor_eq

† indicates names reserved in the Borland implementations or earlier versions of C++.

names beginning with an underscore are reserved for the implementer, but may be used by the programmer (e.g. 75 in C++ 4.0).

names beginning with a $ are reserved for system-dependent variables, and make the code non-portable.

Language Overview Part 1, Page 47

VARIABLE NAMES

• Variable names must start with a letter or underscore and continue with letters, digits, or underscores. Upper and lower case characters are distinct. Variable names starting with a single underscore are generally reserved for the compiler and implementation details, and variable names starting with more than one underscore are generally reserved for the linker.

• By convention, variable names are entirely in lower case (or multi-word variable names may have upper case letters beginning each new word), except symbolic names which are entirely in upper case. Typedef and class names are in mixed case.

• C++ imposes no limitation on variable length, so, in theory, variable names are of unlimited length and kept distinct. However, C compilers had the first 31 characters of the variable name significant. (If more were used, variations occurring after the first 31 identical characters caused unpredictable results.) Many C++ compilers impose practical limits. For maximum compatibility, keep the length of variable names under 32 characters.

• External names (function names and external variable names) may be restricted in length because of implementation details (typically imposed by linkers and loaders). Some restrict these names to as short as 5 characters, but generally you should assume you can use up to 13 character names with reasonable portability.

• C++ is a keyword language, so language keywords may not be used as variable names.

• External names should not duplicate the names of desired external variable names, library functions, or names that are special to the linker. Avoid names like delete, end, getchar, cin, cout, ios, printf, storage, system, or any function names found in the documentation.

• In summary, C++ is a case-sensitive, reserved-word, free-format, block-structured, third generation, object-oriented programming language with no input/output statements.

Part 1, Page 48 C++ Programming

fc3.cpp

Language Overview Part 1, Page 49

/* FC3.CPP: Print Fahrenheit-Celsius table */

Part 1, Page 50 C++ Programming

Language Overview Part 1, Page 51

/* Third version of Fahrenheit-Celsius - KR, pg 13 */ #include <iostream.h> #include <iomanip.h> main() { int fahr; // Fahrenheit temperature for (fahr = 0; fahr <= 300; fahr = fahr + 20) cout << setw(3) << fahr << " " << setw(6) << (5.0/9.0)*(fahr-32) << endl; return 0; }

fc3.cpp EXPLANATION

• This program produces the same answers, but in a different way.

• Most of the variables have been omitted to show that a more complex expression can be used wherever it is valid to use a simple constant.

• The for represents another looping mechanism. It contains three parts separated by semicolons

1. The first part, fahr = 0, is done once before the loop proper is entered. It is the loop initialization.

2. The second part, fahr <= 300, is evaluated before each iteration of the loop. If it is true, the loop is executed (again). It is the loop test condition.

3. The third part, fahr = fahr + 20, is performed after each iteration of the loop. It is the loop re-initialization step. Immediately after re-initialization, the loop test condition is performed again.

• Note that the program is a lot shorter: this makes some parts more obvious and readable (such as the loop), but other parts less obvious and less readable (such as what do 0, 300, and 20 represent).

Part 1, Page 52 C++ Programming

• The flowchart below helps visualize the process being followed with the for statement.

FLOWCHART OF THE for STATEMENT

Language Overview Part 1, Page 53

fc4.cpp

Part 1, Page 54 C++ Programming

/* FC4.CPP: Print Fahrenheit-Celsius table */

Language Overview Part 1, Page 55

Part 1, Page 56 C++ Programming

/* Fourth version Fahrenheit-Celsius KR, page 15 */

Language Overview Part 1, Page 57

Part 1, Page 58 C++ Programming

#include <iostream.h>

Language Overview Part 1, Page 59

Part 1, Page 60 C++ Programming

#include <iomanip.h>

Language Overview Part 1, Page 61

Part 1, Page 62 C++ Programming

Language Overview Part 1, Page 63

Part 1, Page 64 C++ Programming

#define LOWER 0 // lower limit of table #define UPPER 300 // upper limit #define STEP 20 // step size main() { int fahr; // Fahrenheit temperature for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP) cout << setw(3) << fahr << " " <<setprecision(1) << setw(6) << (5.0/9.0)*(fahr-32) << endl; return 0; }

Language Overview Part 1, Page 65

fc4.cpp EXPLANATION

• This program produces the same results as fc2.cpp and fc3.cpp.

• The #define construction provides a symbolic constant that avoids burying "magic numbers" like 0, 300, and 20 in the body of the program.

• By convention, symbolic names are commonly written in upper case so they can be readily distinguished. All other variable names, function names, and commands are written in lower case. Class names, structures, unions, and enumerations will generally be written in mixed case. These are stylistic decisions that should be consistent. Select/develop a style sheet and then follow it.

• The symbolic substitution is made character-for-character and may contain constants, expressions, commands, or anything else. Placing a ; after the constants would be incorrect, since after substitution there would be too many ;'s in the for.

• Most compilers want the # in column 1, the d in column 2, and no imbedded space in symbolic name. The definition ends at the first /* , //, or newline.

Part 1, Page 66 C++ Programming

fc5.cpp /* FC5.CPP: Fifth version Fahrenheit-Celsius */ // print Fahrenheit-Celsius table #include <iostream.h> #include <iomanip.h> main() { const int lower=0, upper=300, step=20; int fahr; cout.flags(ios::fixed); for (fahr = lower; fahr <= upper; fahr = fahr + step) cout << setw(3) << fahr << " " <<setprecision(1) << setw(6) << (5.0/9.0)*(fahr-32) << endl; return 0; }

Language Overview Part 1, Page 67

fc5.cpp EXPLANATION

• This program also prints a table of Fahrenheit to Celsius conversions.

• The problem with the #define construction is that the constants do not have a data type associated with them. This makes type enforcement impossible during the precompile phase.

• C++ uses the const (which is also available on ANSI C compilers with generally less enforcement) to replace the #define construction. Constants have a data type, must be initialized when defined, and cannot have their values altered. A const in C++ is given its value at compile time, and so can be used anywhere a constant is required.

• #define's that define only symbolic constants can (and should) be replaced by a const declaration because of the data typing it provides. This is imperative if the constant is being passed to a function as a parameter.

Part 1, Page 68 C++ Programming

Language Overview Part 1, Page 69

LAB 2 for Part 1

Write a C++ program that will print a table of numbers, their squares, and their cubes. The table should have a heading. Write one version with a "for" loop and a second program version with a "while" loop.

Part 1, Page 70 C++ Programming

fibo1.cpp

Language Overview Part 1, Page 71

/* FIBO1.CPP: Calculate and print fibonacci numbers using

Part 1, Page 72 C++ Programming

Language Overview Part 1, Page 73

a "for" loop */

Part 1, Page 74 C++ Programming

Language Overview Part 1, Page 75

/* Introduces the increment operator "++". */

Part 1, Page 76 C++ Programming

Language Overview Part 1, Page 77

#include <iostream.h>

Part 1, Page 78 C++ Programming

Language Overview Part 1, Page 79

#include <iomanip.h>

Part 1, Page 80 C++ Programming

Language Overview Part 1, Page 81

Part 1, Page 82 C++ Programming

Language Overview Part 1, Page 83

#define LIMIT 20 main() { int x1, // oldest value in sequence x2, // next-oldest value in sequence x3, // new value in sequence i; // loop counter for (i = 1, x1 = 0, x2 = 1; i <= LIMIT; ++i) { x3 = x1 + x2; // calculate new value cout << setw(6) << x3 << endl; // print it x1 = x2; // update what's oldest x2 = x3; // update next oldest } return 0; }

Part 1, Page 84 C++ Programming

fibo1.cpp EXPLANATION

• This program computes the Fibonacci sequence of numbers. Each term in the sequence is the sum of the preceding two.

• For generality, the number of Fibonacci numbers to generate is given as a symbolic constant. (It would be better as a const int.)

• The for loop is used as the control structure. Note that three variables are initialized (i, x1, and x2) as the first part of the for construction

• The re-initialization step is ++i. The ++ is a new operator, which means increment i by one. It could have been written i = i + 1, but ++i is more concise, often more efficient, and definitely easier to read in a more complicated setting such as:

++arb[prm+6][num+8] vs arb[prm+6][num+8] = arb[prm+6][num+8] + 1 In the latter case, you must verify that every character on the right

matches every character on the left before you determine the intent of the statement. In the former case, the intent is clear.

Two fine points (will be covered later):

i=1, x1=0, x2=1 is an example of the comma operator. It evaluates several expressions, returning the value of the last expression on the right. Here is makes no difference, because the result of the overall evaluation of the three expressions is not used.

++i is an example of the prefix increment operator. It increments the operator before using it in subsequent parts of the same expression. Here it makes no difference because it is the entire expression.

Language Overview Part 1, Page 85

RESULTS OF fibo1.cpp 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946

Part 1, Page 86 C++ Programming

GETTING FANCY WITH COMMENTS

• These notes show only one style of comments when using the comment of the form /* ... */. The style shown has the /* immediately precede the comment text, and the */ immediately follow the comment text. Other possible styles are shown below:

/* Style used in these notes, comment delimiters

are tight against text */

/* Open comment / close comment style in which the close comment always starts a new line - takes extra space, but a bit easier to find

*/

/* Extra whitespace style comment in which the

open comment and close comment are both on separate lines - still more space, still easier to find

*/

/********************************************** * Box style - you can’t miss these, but takes * * lots of space, and VERY hard to maintain * **********************************************/

Language Overview Part 1, Page 87

fibo2.cpp /* FIBO2.CPP: Calculate and print fibonacci numbers using a "while" loop. Introduces the increment operator "++" as a side effect. Introduces variable initialization. */ #include <iostream.h> #include <iomanip.h> main() { const int limit = 20; // better than #define int x1 = 0, // oldest value in sequence x2 = 1, // next oldest value in sequence x3, // new value in sequence i = 0; // loop counter while ( ++i <= limit ) { x3 = x1 + x2; // generate new value cout << setw(6) << x3 << endl; // print it x1 = x2; // update oldest value x2 = x3; // update next oldest } return 0; }

Part 1, Page 88 C++ Programming

fibo2.cpp EXPLANATION

• This program produces the same results as fibo1.cpp, but in a different way

• Variables in this program are initialized in their definition. Since these variables appear inside the function, they are initialized each time the function is called.

• The while loop is used as the control structure. However, the ++ operator is used. The expression ++i adds 1 to i before using its value. The expression i++ adds 1 to i after using its value.

• It is the former form that is desired in the while statement so that whenever the new value of i <= LIMIT, we will repeat the loop one more time. This means that i will be incremented before the first time it is used. To correct for that, i is initialized to 0.

• The use of the ++ operator in the while comparison can be thought of as a “side effect.” The primary effect is the while comparison. The side effect is the incrementing of i. Side effects are important in C++, but must be watched closely.

Language Overview Part 1, Page 89

fibo3.cpp /* FIBO3.CPP: Calculate and print fibonacci numbers using a "for" loop. Use double precision floating point instead of integers. Calculate the ratio of two successive terms to show multiple values printed on one line */ #include <iostream.h> #include <iomanip.h> void fibo(int); main() { const int limit = 20; int max = limit; // number of Fibonacci #'s fibo(max); // call a function to do it return 0; } void fibo (int max) { double x1, // oldest value in sequence x2, // next oldest value in sequence x3; // new value to be calculated int i; // loop counter cout.setf(ios::fixed); for (i = 1, x1 = 0.0, x2 = 1.0; i <= max; ++i) { x3 = x1 + x2; // generate next value cout << setprecision(0) << setw(6) << x3 << " " << setprecision(6) << setw(8) << x3/x2 << endl; x1 = x2; // update oldest value x2 = x3; // update next oldest } }

Part 1, Page 90 C++ Programming

fibo3.c EXPLANATION

• This program also computes the Fibonacci sequence of numbers. However, this time it uses double precision real numbers.

• This program also computes the ratio of adjacent terms in the Fibonacci sequence to show that it converges to the golden ratio.

• In case you tire of naming all your functions main, this function is named fibo, and has one parameter, the number of terms that will be printed.

• Communication between functions can take place by means of arguments. The parentheses following the function name surround the argument list. If there are no arguments, the function name is followed by ().

• Both the function itself (for the return value), and all of its parameters must be data-typed. The function type is defined before the function name, and the type of each parameter is declared before the formal parameter.

• The parameter is used in the function in much the same way that the symbol LIMIT was used in earlier versions. The important difference is that the parameter is a variable which can be altered.

• The function main() is still needed. It defines the variable max (needed to call fibo) and initializes it, using constant limit.

Language Overview Part 1, Page 91

RESULTS OF fibo3.cpp 1 1.000000 2 2.000000 3 1.500000 5 1.666667 8 1.600000 13 1.625000 21 1.615385 34 1.619048 55 1.617647 89 1.618182 144 1.617978 233 1.618056 377 1.618026 610 1.618037 987 1.618033 1597 1.618034 2584 1.618034 4181 1.618034 6765 1.618034 10946 1.618034

Part 1, Page 92 C++ Programming

FUNCTION PROTOTYPING

• In this program, the function fibo is written using ANSI C function prototyping. This prototyping must be strictly adhered to in C++.

• The functions main() and fibo(max) can appear in any order in the same file, or, with additional statements to keep the compiler and linker happy, in two separate files. In this case the function main() appears first.

• The file iostream.h contains (among other things) a declaration for the object cout and the operator << invoked within main. The function fibo is also invoked within main, and before being invoked the function main must know the data type(s) of the input(s) to fibo and the type of the return value, if any. This information is provided by the declaration of fibo that appears just before the definition of the function main. It declares that fibo will have one integer parameters and return no result.

• The general form of a function prototype is: type name (typed-argument-list); The function prototype in this example could have been written as: void fibo(int); or as: void fibo(int number); number could have been anything, does not need to match the definition, and does not define or declare a variable by that name. Typically it is there as a placeholder, and should generally be descriptive. One common technique is to just copy the first line of the function definition followed by a semicolon to produce: void fibo(int max);

• The general form of a function (definition) is: type name(typed-argument-list) { declarations statements }

Language Overview Part 1, Page 93

fibo4.cpp /* FIBO4.CPP: Calculate and print a variable number of fibonacci numbers */ #include <iostream.h> #include <iomanip.h> void fibo(int); main() { const int limit = 30; int max; // number of Fibonacci #'s cout << "How many Fibonacci numbers? "; cin >> max; if (max < 1) max = 1; if (max > limit) max = limit; fibo(max); // call a function to do it return 0; } void fibo (int max) { double x1, // oldest value in sequence x2, // next oldest value in sequence x3; // new value to be calculated int i; // loop counter cout.setf(ios::fixed); for (i = 1, x1 = 0.0, x2 = 1.0; i <= max; ++i) { x3 = x1 + x2; // generate next value cout << setprecision(0) << setw(6) << x3 << " " << setprecision(6) << setw(8) << x3/x2 << endl; x1 = x2; // update oldest value x2 = x3; // update next oldest } }

Part 1, Page 94 C++ Programming

fibo4.cpp EXPLANATION

• This program provides for user interaction by allowing the user to specify the number of Fibonacci numbers generated.

• First the user is sent the prompt by inserting a string constant into the output stream. Notice that a newline is not sent, nor is the endl manipulator used. This will keep the screen cursor position on the same line as the prompt, just following it.

• User input is accepted via the >> (extraction) operator. The request for data extraction from the cin input stream automatically causes a flush of the cout output stream so that we can be assured that the user sees the prompt before having to respond to it.

• Since an integer is being extracted, all preceding whitespace will be accepted and discarded, followed by as many consecutive decimal digits as the user chooses to enter. All input after the last digit (such as a newline) will be left in the input stream to await the next extraction.

• The user input is then checked for validity. In this case, it is simply checked to see if the value is either too small or too large, and, if so, the program silently alters the invalid input to a legal value. Obviously, more user interaction could be written to force the user to enter a legal value.

Language Overview Part 1, Page 95

RESULTS OF fibo4.cpp How many Fibonacci numbers? 9 1 1.000000 2 2.000000 3 1.500000 5 1.666667 8 1.600000 13 1.625000 21 1.615385 34 1.619048 55 1.617647

Part 1, Page 96 C++ Programming

cpy1.cpp /* CPY1.CPP: Copy input to output; 1st version */ /* From KR pg 16 */ #include <iostream.h> main() { char c; // input character cin.get(c); // read a character while ( cin ) // check for EOF { cout.put(c); // write a char. cin.get(c); // read next char. } return 0; }

cpy1.cpp EXPLANATION

• This program copies terminal input to terminal output.

• The program uses two input/output functions, get(c) and put(c). The executable code for these functions are contained in the C++ library supplied with the compiler. Data type and parameter information about these functions must be available to the calling function at compile time. This is done via the statement #include <iostream.h>.

• The function get(c) fetches the next input character each time it is called and places it in c. This could be any printable character or any control character not seized by the terminal driver or operating system.

• The function put(c) sends the character c to terminal output each time it is called. Any character may be sent. Multiple character output from cout << may be interleaved with single character output.

Language Overview Part 1, Page 97

cpy1.cpp EXPLANATION - END OF FILE

• Detecting end-of-file is a potential problem. We don't want end-of-file to be interpreted as just another character (or we will run past the end-of-file when processing characters). Therefore we need a mechanism other than checking the value of the character returned to determine if an end-of-file was encountered.

• When cin is used by itself (in the logical expression controlling the while loop) it returns true if the last input succeeded (no end of file), false otherwise.

• The mechanism used by C++ is storing a stream status value in the object cin. This status is checked by using cin in a logical expression. If everything went fine, cin will evaluate to true. If anything went wrong, cin will return false. In the above program, we don’t check what went wrong, we just assume it was an end-of-file. (The section on input/output contains details of how to check for various types of errors.)

• Note that the end-of-file checking does not “read ahead” to see if the character it just read was the last character before the end-of-file. End-of-file is only detected after reading past the last character and encountering an end-of-file instead of a valid character. Thus, the checking needs to be done after attempting to read a character and before attempting to use the character read.

• On UNIX systems, ^D (Control-D) at the beginning of a line is used as the end-of-file. In VMS, DOS, and CPM, ^Z (Control-Z) is used as the end-of-file. In general, end-of-file marks should be placed at the beginning of a line so that it is preceded in the file by a newline (or carriage return/line feed).

Part 1, Page 98 C++ Programming

cpy2.cpp /* CPY2.CPP: Copy input to output; 2nd version */ /* Introduces the fact that the function also returns a value. - From KR, page 17 */ #include <iostream.h> main() { char c; // input character while ( cin.get(c) ) // grab & check cout.put(c); return 0; }

cpy2.cpp EXPLANATION

• This program is identical in function to cpy1.cpp.

• It is written more concisely than the previous one

• The fundamental notion here is that the function call to get(c) not only puts a character in c, but also returns the stream status that can be used as a logical value.

Language Overview Part 1, Page 99

ccnt1.cpp // CCNT1.CPP: Count characters in input; 1st version // From KR, page 18 #include <iostream.h> main() { char c; // input character - unused long nc; // character count nc = 0; // start it at 0 while( cin.get(c) ) ++nc; cout << nc << " characters" << endl; return 0; }

Part 1, Page 100 C++ Programming

ccnt1.cpp EXPLANATION

• This program counts the number of characters given as input. All characters passed by the system to the program are counted including newlines.

• The counter, nc, is declared to be of type long (long int is identical and preferable) instead of type int because it is possible that standard sized integers might only handle values up to 32767 (such as on most IBM PC compilers). In fact, it would make no difference on many compilers where both standard sized and long integers can handle values up to 2,147,483,647.

• The statement ++nc, seen before in the Fibonacci program, increments the counter within the while loop.

• The minimum ranges of the various data types are:

char 8 bits

signed char ±127

unsigned char 255

short int ±32,767

unsigned short int 65,535

int ±32,767

unsigned int 65,535

long int ±2,147,483,647

unsigned long int 4,294,967,295

float 6 decimal digits, 1E±37 range

double 10 decimal digits, 1E±37 range

Language Overview Part 1, Page 101

ccnt2.cpp // CCNT2.CPP: count characters in input; 2nd version // From KR, page 18 #include <iostream.h> main() { char c; // input character double nc; // character count for (nc = 0; cin.get(c); ++nc) ; // note the empty statement cout << "character count = " << nc << endl; return 0; }

Part 1, Page 102 C++ Programming

ccnt2.cpp EXPLANATION

• This program also counts the number of characters given as input, but the output is not identical (the output is labeled differently).

• The program uses double precision floating point numbers. These have the highest range, and will never "overflow." However, once the value exceeds approximately 14 digits (perhaps as few as 10 digits in some implementations), the program will, in effect, stop counting by 1's. This program will also run more slowly since double precision floating point operations can take 1.5 to 20 times as long as standard integer operations.

• The program uses a for statement instead of a while statement. All of the necessary operations are done as parts of the loop definition. However, the for construction still requires a statement in the loop, so it is provided with a null statement, consisting of an isolated semicolon.

• Note that in both programs, the loop testing is done at the top of the loop, providing for correct handling of the situation in which the input contains no characters. It is important that programs behave properly at boundary values and in unusual situations. Programs should always be thoroughly tested for proper behavior in these situations.

Language Overview Part 1, Page 103

lcnt.cpp

Part 1, Page 104 C++ Programming

/* LCNT.CPP: Count lines in input */

Language Overview Part 1, Page 105

Part 1, Page 106 C++ Programming

/* From KR, page 17 */

Language Overview Part 1, Page 107

Part 1, Page 108 C++ Programming

#include <iostream.h>

Language Overview Part 1, Page 109

Part 1, Page 110 C++ Programming

Language Overview Part 1, Page 111

Part 1, Page 112 C++ Programming

main()

Language Overview Part 1, Page 113

Part 1, Page 114 C++ Programming

{

Language Overview Part 1, Page 115

Part 1, Page 116 C++ Programming

char c; // input character

Language Overview Part 1, Page 117

Part 1, Page 118 C++ Programming

int nl; // line count nl = 0; // set counter to 0 while( cin.get(c) ) if( c == '\n' ) ++nl; cout << "line count = " << nl << endl; return 0; }

Language Overview Part 1, Page 119

lcnt.cpp EXPLANATION

• This program counts the number of lines of input. (Actually it is counting the number of newline characters that act as line separators in the UNIX environment.)

• The body of the while loop contains an if statement. The if statement tests the parenthesized condition, expression, or value. If it is true (evaluates to non-zero), the statement following the condition is executed.

• The == is the C notation for “is equal to.” Since assignment is done about twice as often as testing for equality, it is appropriate that the assignment operator be shorter than the operator that tests for equality. You can also use the preprocessor directive

#define EQ == and use EQ instead of == in the program. (Using = for == is a

common mistake that, unfortunately, is syntactically correct.) The practice of using EQ for ==, in vogue in the mid-1980’s, is not currently considered good programming practice.

• Any single character can be written between single quotes. It produces a value equal to the numerical value of the character in the machine's character set. This is called a character constant. On a computer with the ASCII character set, usually 'A' is 65, 'B' is 66, etc..; 'a' is 97, 'b' is 98, etc.; '0' is 48, '1' is 49, etc.

• Escape sequences used in character strings are also legal in character constants. In this program '\n' stands for the value of the newline character. It is regarded as a single character, and in expressions is equivalent to a single integer. On an ASCII computer, newline is 10 (the line-feed character).

Part 1, Page 120 C++ Programming

ESCAPE SEQUENCES IN C++

sequence meaning

\a alert (bell) \b backspace \f formfeed \n newline \r carriage return \t horizontal tab \v vertical tab \\ backslash \? question mark \’ single quote \” double quote \0 null \0ooo octal number \xhh hexadecimal number

Language Overview Part 1, Page 121

LAB 3 for Part 1

1. (K&R Exercise 1-9) Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

2. Revise the C++ program from lab 2 that will print a table of numbers, their squares, and their cubes. Write two functions, one for squaring numbers and the second for cubing numbers. Call these functions to create the table instead of doing the computations within main.

Part 1, Page 122 C++ Programming

wcnt1.cpp

Language Overview Part 1, Page 123

/* WCNT1.CPP: Count the words in terminal input.

Part 1, Page 124 C++ Programming

Language Overview Part 1, Page 125

A new word is encountered when we go from a blank

Part 1, Page 126 C++ Programming

Language Overview Part 1, Page 127

(space or newline or tab) to a non-blank character. Based on KR, page 20. A function is defined to test a character for "blankness". */ #include <iostream.h> bool isa_blank(int); main() { char c, // current character c_old; // last character int words; // number of words c_old = ' '; words = 0; while( cin.get(c) ) { if( isa_blank(c_old) && !isa_blank(c) ) ++ words; c_old = c; } cout << "Number of words = " << words << endl; return 0; } bool isa_blank(int x) { if( x == ' ' || x == '\n' || x == '\t' ) return(true); else return(false); }

Part 1, Page 128 C++ Programming

wcnt1.cpp EXPLANATION

• This program counts the number of words in terminal input. A word is defined as a transition from a space, newline, or tab to a non-blank character.

• This program uses a function to determine if a character is a blank. The function isa_blank(x) returns true if the character x is a blank, newline, or tab; returns false otherwise.

• The operator || means OR; && means AND. The character \t is the visible representation of tab. Logical expressions are evaluated left to right only until the truth or falseness is known, then stops. This is important if the logical parts contain side effects.

• The main program repeatedly compares the previous character with the current character. Whenever a blank to non-blank transition is made, the word count is incremented.

• The main program is not very efficient since each character of input is tested for "blankness" twice, once as the current character and once as the previous character. The code, however, is very easy to read.

Language Overview Part 1, Page 129

wcnt2.cpp /* WCNT2.CPP: Count lines, words, and characters in input based on KR - page 20 */ #include <iostream.h> #define YES 1 /* inside a word */ #define NO 0 /* outside a word */ main() { char c; // input character int lines, // line count words, // word count chars, // character count inword; /* flag (YES if within a word, NO if within blanks */ inword = NO; lines = words = chars = 0; while ( cin.get(c) ) { ++chars; if (c == '\n') ++lines; if (c == ' ' || c == '\n' || c == '\t') inword = NO; else if ( inword == NO ) { inword = YES; ++words; /* increment on white-space to non-white-space transition */ } } cout << lines << " lines, " << words << " words, " << chars << " characters\n"; return 0; }

Part 1, Page 130 C++ Programming

wcnt2.cpp EXPLANATION

• This program counts lines, words, and characters as previously defined.

• The program uses the “logical” variable inword. Previously C++ did not have a built-in logical data type, so an integer was (and still can be) used with 0 for NO (or false) and 1 for YES. Symbolic names and comments are used to make this concept clear.

• The program is more efficient than the previous one because each character of input is tested for each condition only once. Essentially, the logical status variable replaced the redundant test.

• The multiple assignment statement lines = words = chars = 0 Is a special case of the notion that assignment yields a value.

Assignment is done right-to-left, so 0 is evaluated, stored in chars, yields a value of 0 which is stored in words. The second assignment in turn also yields a value of 0 which is finally stored in lines.

• The second if statement in the program contains the more general structure

if (expression) statement-1 else statement-2 The else part happens to contain another if statement. In this

structure exactly one of the two statements is executed.

Language Overview Part 1, Page 131

dcnt.cpp /* DCNT.CPP: Count the digits, white space and other characters in terminal input. Introduces arrays. */ // From KR, page 22 #include <iostream.h> main() { char c; // input character int i, // loop counter nwhite, // whitespace count nother; // count of other characters int ndigit[10]; // define an array of int // with 10 terms, subscripted 0 to 9 nwhite = nother = 0; // zero out counters for ( i = 0; i < 10; ++i) // zero counter array ndigit[i] = 0; while ( cin.get(c) ) if (c >= '0' && c <= '9') ++ndigit[c-'0']; else if ( c == ' ' || c == '\n' || c == '\t' ) ++nwhite; else ++nother; cout << "digits ="; // note no newline for ( i = 0; i < 10; ++i) cout << ' ' << ndigit[i]; // no newline cout << "\nwhite space = " << nwhite; cout << ", other = " << nother << endl; return 0; }

Part 1, Page 132 C++ Programming

dcnt.cpp EXPLANATION

• This program counts the number of 0's, 1's, ... , 9's, white characters (blank, tab, or newline), and all other characters. Twelve totals are too cumbersome to keep by brute force. An array will be used to keep count of the number of occurrences of each digit.

• The definition int ndigit[10]; defines ndigit to be an array of 10 integers. Array subscripts in C++ start at 0, so the elements of the array are:

ndigit[0], ndigit[1], ndigit[2], ... , ndigit[9]

• A subscript can be any integer expression. No bounds checking is done on any array subscripts. There is no debugger available that checks array subscripts either. Overrunning or underrunning an array merely grabs data stored in memory somewhere outside the array.

• The program relies heavily on the organization of the character set, although not on the particular representation of the characters. It counts on the characters 0, 1, ... , 9 occupying adjacent, increasing positions in the character set. Fortunately this is true for all modern conventional character sets.

• The test

if (c >= '0' && c <= '9') ...

determines if the character in c is a digit. If so, the numeric value of that digit is c - '0'. (There are better ways of doing this using the library functions isdigit and atoi.)

• When entering a program, make sure the correct quote key is used around character constants. There are two single quote keys, "open single quote" and "close single quote." Either may be slanted or vertical. You want the "close single quote" which is the one that has the most forward slant. (Given the choice between ` and ', use '; the key usually has " as its uppercase.)

• By definition, arithmetic involving characters and integers converts everything to integer before proceeding.

Language Overview Part 1, Page 133

COMPARISON AND LOGICAL OPERATORS

Comparison Operator Alternative Form Meaning

> greater than < less than >= greater than or equal to <= less than or equal to == equal to != not_eq not equal to

Logical Operator Alternative Form Meaning

&& and logical and || or logical or ! not logical not

Part 1, Page 134 C++ Programming

dcnt.cpp EXPLANATION OF if CONSTRUCTION

• The construction if (condition) statement else if (condition) statement else statement occurs frequently to express a multi-way decision. It continues testing

until some condition is met. As a matter of style, we do not continue the indentation lest our program march off the right side of the page.

Language Overview Part 1, Page 135

powr1.cpp

Part 1, Page 136 C++ Programming

/* POWR1.CPP: Power function - version 1 */

Language Overview Part 1, Page 137

Part 1, Page 138 C++ Programming

/* From KR, pages 24-25 */

Language Overview Part 1, Page 139

Part 1, Page 140 C++ Programming

#include <iostream.h>

Language Overview Part 1, Page 141

Part 1, Page 142 C++ Programming

Language Overview Part 1, Page 143

Part 1, Page 144 C++ Programming

int power(int, int); // test power function main() { int i; // loop counter for ( i = 0; i < 10; ++i) cout << i << " " << power(2,i) << " " << power(-3,i) << endl; return 0; } // power: raise base to n-th power; n >= 0 int power(int base, int n) { int i, // loop counter p; // result p = 1; // (base ** 0) = 1 for ( i = 1; i <= n; ++i) p = p * base; return(p); }

Language Overview Part 1, Page 145

powr1.cpp EXPLANATION

• A function in C++ is equivalent to a subroutine or function in FORTRAN or a procedure in PL/I, Pascal, etc. Functions allow encapsulation of computations, etc. into black boxes.

• In large program design, functions are necessary to cope with the combinatorial explosion of complexity. Modular design dictates that functions, unless lengthy itemizations, occupy no more than one page. Classes in C++ rely on member functions to make changes to the object states that are encapsulated in the objects. This usually results in writing lots of short functions, some with little more than one line of code.

• Since C++ has no exponentiation operator, we need to use a power function. (This function is commonly included in the math library as pow(double x, double y). The math library declarations can be obtained by including the file math.h. The actual code for the functions are obtained when the C++ program is linked.)

• The functions main() and power(base,n) can appear in any order in the same file, or, with additional statements to keep the compiler and linker happy, in two separate files. In this case the function main() appears first.

• The file iostream.h contains (among other things) a declaration for the object cout used within main. The function power is also invoked within main, and before being invoked the function main must know the data types of the inputs to power and the type of the return value. This information is provided by the declaration of power that appears just before the definition of the function main. It declares that power will have two integer parameters and return an integer result.

Part 1, Page 146 C++ Programming

powr2.cpp /* POWR2.CPP: Power function - version 2 */ #include <iostream.h> int power(int, int); // test power function main() { int i; // loop counter for ( i = 0; i < 10; ++i) cout << i << " " << power(2,i) << " " << power(-3,i) << endl; return 0; } // power: raise base to n-th power; n >= 0 // version 2. KR, page 27 int power(int base, int n) { int p; // result for ( p = 1; n > 0; --n) p = p * base; return(p); }

Language Overview Part 1, Page 147

RETURN and powr2.cpp EXPLANATION

• The return statement can have an argument, in which case the value is returned to the calling function. If the return has no argument, or you "fall off the end" of the function, no useful value is returned. (Note that this is very different than in languages like FORTRAN or Pascal where a value is returned by assigning a value to the function name.)

• The value could have been returned in either of the following ways: return p; return (p);

Generally, a single variable or constant is not put in parentheses, but an expression is, just for clarity.

• Variables used in the power function are purely local to the function. They do not conflict with variables in the function main. Values are given to the parameters when the function is invoked, and a value is possibly returned after completion of the function. Even if the value of the variables base and n were altered within the function power, the corresponding values of the arguments in the calling function main would remain unchanged. Thus the function on the facing page would have worked just as well.

Part 1, Page 148 C++ Programming

Outline for a Properly Constructed Program

• Introductory comments

- Name of file containing the code

- Date written

- Author

- General purpose of the code

• #include statements

- System libraries #include < ... >

- User libraries #include " ... "

• #define statements

- Symbolic constants

- Macros

• Structure, union, and typedef declarations

• Function declarations

• Global variables

• main

• Other functions

Language Overview Part 1, Page 149

LAB 4 for Part 1

Write a main function to compute the average of an array of ten numbers. Fill the array with initial values using assignment statements or using the extraction operator.

Part 1, Page 150 C++ Programming

powr3.cpp /* POWR3.CPP: Power function - version 3 */ #include <iostream.h> int power(int, int); // test power function main() { int i; // loop counter for ( i = 0; i < 10; ++i) cout << i << " " << power(2,i) << " " << power(-3,i) << endl; return 0; } // power: raise base to n-th power; n >= 0 // version 3 - using recursion int power(int base, int n) { int p; // result if (n == 0) p = 1; // (base ** 0) = 1 else p = base * power(base, n-1); return(p); }

Language Overview Part 1, Page 151

powr3.cpp EXPLANATION

• This program uses the concept of recursion - a function that calls itself. Not all languages or all dialects of a language support recursion. It is an integral part of C++.

• Programmers using recursion must be careful to avoid creating an infinite loop. The function as written will terminate for all integer values of n >= 0. However, if a negative value of n is provided, the program will call itself until it crashes. This could be corrected by altering the test to:

if (n <= 0)

• For small machines using recursion with a large number of recursive calls, you need to worry about "stack space" in the machine. For example, the default stack length for Borland C++ compilers on IBM PC’s is only 4096 bytes. (This can be increased in the Borland compilers by setting the global variable _stklen to a larger value at the beginning of the code. This “fix” is implementation specific.)

• Iteration and recursion are alternatives.

Part 1, Page 152 C++ Programming

maxlin1.cpp /* MAXLIN1.CPP: Find & print the longest line from input. All functions in a single file, parameters passed */ #include <iostream.h> int getline(char [], int); void copy(char [], char []); main() // Computes and prints the longest line { const int maxline = 1000; // maximum input line size int len, // current line length max = 0; // maximum length seen so far char line[maxline], // current input line save[maxline]; // longest line saved here while ( (len = getline(line, maxline)) > 0 ) if (len > max) // beat previous length { max = len; // record this length copy(save, line); // and save line } if (max > 0) // there was a line { cout << "\nlength of longest line: " << (max-1); cout << "\nthe longest line is:\n\n"; cout << save << endl; } return 0; }

Language Overview Part 1, Page 153

maxlin1.cpp EXPLANATION

• This program saves the longest line input so far, and at the end prints out the contents of the longest line in the file (if there was a non-zero-length line).

• Since C++ has no built-in string data type (there is, however, a class library that implements a sting data type), we instead use an array of characters terminated by a null (a binary zero byte, obtained by \0). This method of storing strings should be mastered because this is the way string constants are stored, the way command line parameters are passed, and, ultimately, the way the actual data is probably stored even when a string data type is provided by a class library.

• The program is divided up into three functions. The function main() obtains a line (by calling getline), checks to see if it is of championship length, if it is, updates the champion value and copies the champ into the record book. After the end-of-file is encountered, it checks to see if anything is in the record book, and, if there is, prints it out.

Part 1, Page 154 C++ Programming

maxlin1.cpp (continued) /* Get input line into array s. The function getline returns the length of the input line, including a newline character, if present. The array s is terminated with an ascii null */ int getline(char s[], int lim) { char c; // input character int i = 0; // intra-line counter while( i<lim-1 && cin.get(c) && c != '\n' ) s[i++] = c; if (c == '\n') // did we fall out with a \n? s[i++] = c; // if so, keep it s[i] = '\0'; // always terminate strings! return(i); } /* copy: copy 'from' into 'to'; assume 'to' is big enough */ void copy(char to[], char from[]) { int i = 0; // string position counter while( (to[i] = from[i]) != '\0' ) // move & check ++i; }

Language Overview Part 1, Page 155

maxlin1.cpp EXPLANATION (Continued)

• The function getline(s, lim) inputs a line of up to lim characters into a character array s that stores data like a string. The array s contains the contents of the input line, including the newline character and a string-terminating null. The function value itself is the line length.

• The function copy(to, from) copies the second string to the first string. It does not return a value

• The length of the string array char s[] is not specified in the function getline(s, lim) since it is determined in main. The function only needs to know the type and the fact that it is an array. Simple (scalar) variables are passed by value, meaning that a copy of the data is put on the calling stack. Arrays, however, are passed by reference, meaning that a pointer (memory address) to the beginning of the array is put on the calling stack. Thus when a function modifies an array, it is not modifying a copy of the data, but the original data stored in the calling program.

• The function getline(s, lim) puts the character \0 (the null character) at the end of the array it is filling to mark the end of the string. This convention must be adhered to in creating C++ default character strings so that all string processing functions can detect the end of the string.

Part 1, Page 156 C++ Programming

hello4.cpp // HELLO4.CPP: Personalized greetings #include <iostream.h> // declarations of stream I/O main() { char name[10]; cout << "What is your name? "; cin >> name; // possible array overrun cout << "Hello " << name << " and welcome to C++\n"; return 0; }

hello5.cpp /* HELLO5.CPP: Personalized greetings - avoiding array overrun */ #include <iostream.h> // declarations of stream I/O main() { char name[10]; cout << "What is your name? "; cin.width(sizeof(name)); //avoids overflow cin >> name; cout << "Hello " << name << " and welcome to C++\n"; return 0; }

Language Overview Part 1, Page 157

hello4.cpp AND hello5.cpp EXPLANATION

• C++ uses the extraction (get from) operator on the cin stream to obtain data of any built-in type or a character string. (It will also be “overloaded” for user-defined classes to extract data of any user-defined type.)

• By default, the extraction operator gets a data item of the appropriate type, ignoring all preceding whitespace (as defined by the function isspace in ctype.h)

• In hello4.cpp, we are attempting to input a string. (The string is terminated by whitespace.) The string, by default, is of unlimited length. The array receiving the string, however, is not of unlimited length. This can cause the array to be overrun by a careless (or long-named) user.

• hello5.cpp corrects the array overrun problem by setting the width allowed. It does this by modifying a variable in the class istream (which is a derived class of ios). The sizeof operator reports how many bytes of memory an object occupies.

Part 1, Page 158 C++ Programming

Language Overview Part 1, Page 159

LAB 5 for Part 1

1. (Easy) Write a program to remove trailing blanks from each line of input.

2. (Medium) Write a program to remove trailing blanks from each line of input, and delete entirely blank lines.

3. (Medium hard) (K&R Exercise 1-18) Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.

4. (Medium) Write a program to remove all text after // from each line of input, as well as the //. In effect, this is removing all end-of-line comments.

5. (Hard) Write a program to remove all text after /*, until the next */ appears (which may not be on the same line). The starting /* and the ending */ are to be removed along with the text in between.

6. (Easy to Medium) Write a function for computing the average of an array of n numbers, passing it a pointer to the array (the array name) and an integer, n, the number of valid elements in the array. Return the average as a double precision value. Create the array in main, fill the array from user input in main, and do all input/output from main.

Part 1, Page 160 C++ Programming

Supplemental Exercises for Part 1

1. Write a program to replace any combination of blanks and tabs with a single blank.

2. Write a program to replace tabs with the appropriate number of spaces. Assume tabs are set at 9, 17, 25, etc. (every 8 positions).

3. (Challenge) (K&R Exercise 1-23) Write a program to remove all comments from a C++ program. Don't forget to handle quoted strings and character constants properly. Remember that C++ comments of the form /* ... */ do not nest.