Sei sulla pagina 1di 113

Beginning Programming in C++

Units of Study
Please refer to Terms of Use

Computer Science 1 First Semester Unit 1: Introduction Using Visual C++ Environment Screen Manipulations Unit 2: Data Basics AP Strings Unit 3: Conditionals Unit 4: Looping Unit 5: Functions Mid Year Review

Computer Science 2 Second Semester Unit 6: Library Functions Unit 7: Files Unit 8: Arrays Unit 9: Structures Unit 10: Pointers Final Assessment

WEBSITE: http://mathbits.com/MathBits/CompSci/compsci.htm

A Brief History of C++


In the early 1970s, Dennis Ritchie of Bell Laboratories was engaged in a project to develop a new operating system. Ritchie discovered that in order to accomplish his task he needed the use of a programming language that was concise and that produced compact and speedy programs. This need led Ritchie to develop the programming language called C. In the early 1980's, also at Bell Laboratories, another programming language was created which was based upon the C language. This new language was developed by Bjarne Stroustrup and was called C++. Stroustrup states that the purpose of C++ is to make writing good programs easier and more pleasant for the individual programmer. When he designed C++, he added OOP (Object Oriented Programming) features to C without significantly changing the C component. Thus C++ is a "relative" (called a superset) of C, meaning that any valid C program is also a valid C++ program. There are several versions of the C++ language, of which Visual C++ is only one. Other dialects include Borland C++, Turbo C++, and Code Warrior (Mac). All of these software packages enable you to create computer programs with C++, but they all implement the C++ language in a slightly different manner. In an attempt to maintain portability of both the C and C++ languages, the American National Standards Institute (ANSI) developed a standard of consistency for C and C++ programming. While we will be working primarily with this ANSI standard, we will also be examining the idiosyncrasies of Microsoft Visual C++ 6.0.

Note: Due to their power and ease of use, C and C++ were used in the programming of the special effects for Star Wars.

Needed Acronyms
You will need to be familiar with the following acronyms associated with computer programming. You will see references to these acronyms throughout your study of C++.
Simplistic descriptions are all that will be needed at this point.

ALU - Arithmetic Logic Unit - the part of the processor which performs =, +, -, < , >,
etc. operations and comparisons.

CRT - Cathode Ray Tube - an electrical device found in monitors for displaying images
by exciting phosphor dots with a scanned electron beam. CRT is often used to refer to the monitor.

CPU - Central Processing Unit - the heart (brains) of the computer system. It is
comprised of the control unit, the arithmetic logic unit, and temporary storage (RAM).

DOS - Disk Operating System - was the first widely-installed operating system for
personal computers developed for IBM by Microsoft. It is software used in most computer systems to manage storage devices as well as data of any kind, including files. It is referred to as a "disk" operating system because the storage devices are made of rotating platters.

IDE - Integrated Development Environment - a system where you can control the
editing and compiling of language code from one program.

LAN - Local Area Network - a set of computers connected in order to share programs
and storage space. "Local" implies that the network is contained within a relatively small

space, such as a classroom, an office, one section of the building, or one building.

OOP - Object Oriented Programming - the use of small, reusable components to


construct large software systems.

OS - Operating System - the program that manages all the other programs in a computer.
Some popular operating systems include MS-DOS, Windows 98/2000/NT/XP, MacOS, Unix, and Linux.

RAM - Random Access Memory - temporary memory lost when the computer is turned
off.

ROM - Read Only Memory - hardwired memory which cannot be changed. Contains
the system directions.

Vocabulary
You will need to have an intuitive understanding of certain terms associated with computer programming. You will see references to these terms throughout your study of C++. The descriptions stated here are "intuitive" statements and are not intended to be definitive definitions for these terms.

Hardware - the "machinery" - computer equipment - the CPU, the monitor, the keyboard,
the mouse, the external speakers, the scanner, the printer, etc. The physical, touchable parts of a computer system.

Software - the program instructions that make the computer do some task, such as word
process, manage databases, play games, etc. Your C++ programs will be your software.

Program - a listing of instructions (code) for the computer to follow written in some
programming language. For this course, these instructions will be written in the language of C++.

Hard Copy - a paper printout of the program code or data displayed on the screen. Soft Copy - copy of a program stored on a hard drive, diskette, or CD. Network - a hardware and software data communication system. Usually a group of
computers that are linked to share memory and programs.

Control Unit - the unit inside of the CPU which "directs the traffic" - makes decisions. It

performs the functions of fetch, decode, execute, and store.

Machine Language - the lowest level of computer languages where instructions are
given by numeric code.

High Level Language - a computer language which is easily read by humans - the code
consists of English-like words where each statement corresponds to several machine language instructions.

Object Code - the machine code version of the source program (a program written by a
programmer).

Compiler - converts the source code of a program to machine language placing the result
in an object code file.

Interpreter - converts a program one line at a time into machine language. Bit - the representation of a 1 or 0 designating power ON or power OFF. A binary digit. Byte - 8 bits. Kilobyte - approximately 1000 bytes (1024 bytes) Megabyte - approximately 1,000,000 bytes (1,048,576 bytes) Gigabyte - approximately a billion bytes (1,073,741,824 bytes)
Why are the actual number of bytes "more" than what we expect them to be? We are thinking "kilo" in base 10 while the computer is thinking "kilo" in base 2.

Format/Initialize - to prepare a storage device (diskette or hard disk) for receiving


information for a system. The storage device is said to be formatted (into areas called sectors and tracks) when its space has been divided and organized into areas that can be quickly controlled by the system for storage and access.

The Four Equipment Functions of a Computer System


There are four main equipment functions of a computer system:

Input, Processing, Storage and Output

Input: the transferring of information into a computer system - for our purposes this will
be accomplished when you, the programmer, type source code at the keyboard or open a previously typed program.

Processing: the manipulation and control of information within the computer system.
Such manipulations are handled by the Control Unit, the Arithmetic Logic Unit and Temporary Storage.

Storage: the means by which information can be "permanently" saved (until such time as
you wish to delete it). This usually occurs on a hard drive, a diskette or a CD.

Output: the displaying of information - for our purposes this will be accomplished when
your program displays information on the monitor or printed on paper.

Working with Number Bases


One of the skills which is useful to programmers is an understanding of the relationship between number bases. When you understand how numbers are represented in base two (Binary), base eight (Octal), and base sixteen (Hexadecimal), you will better understand references which will be made later in your study of C++.

The number system that we all know and love is the Decimal number system, base 10. In our number system we utilize the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. All numbers are formed by combining these digits. Other number bases work in the same manner only with different digits. The Binary number system, base 2, uses only the digits 0 and 1. The Octal number system, base 8, uses the digits 0, 1, 2, 3, 4, 5, 6, and 7. The Hexadecimal number system, base 16, uses the digits and letters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. Notice how, in each of these number systems, the number of digits contained within the system is the name of the system. Base 2 has 2 digits, Base 10 has 10 digits, and so on. Just be careful to remember that each system starts counting with 0. Each system uses its digits to form all of the numbers contained within the system. In the number system that we know and love, base 10, we are familiar with the terms "ones", "tens", "hundreds", "thousands", etc. used to describe the position a digit holds within a number. These terms are actually words that describe powers of 10. The positions within a number in base 10 are formed by systematically raising the number 10 to various powers. 100 = 1 101 = 10 102 = 100 103 = 1000 (ones) (tens) (hundreds) (thousands)

The same process is used to create numbers in other number systems as well. The only difference is that instead of raising 10 to a power, the new base number is used. For example, when working in base 8, you are working with powers of 8 (80, 81, 82, 83, ...). Base 2 works with powers of 2, base 16 works with powers of 16, and so on. In your study of computer programming, most of your references will be made to the binary number system. The simplicity of only dealing with two digits (0 or 1) is very appealing to a computer system. The 0 and 1 can represent current being turned OFF or ON. Notice how switches on computer hardware often display a 0 or a 1 to represent off or on. Now, let's go on to the next lesson page and look at how to convert from one number base to another.

Change a number from base 10 to any other base:

Let's see if we can convert some numbers from one base to another. There are many ways to work with number base conversions. We will be discussing only one method. Please feel free to use any conversion system with which you are comfortable. Don't panic! Yes, it is math. But you can do it!

Example 1: Convert 510 (read 5 base 10) into base 2.


The Process:
1. Divide the "desired" base (in this case base 2) INTO the number you are trying to convert. 2. Write the quotient (the answer) with a remainder like you did in elementary school. 3. Repeat this division process using the whole number from the previous quotient (the number in front of the remainder). 4. Continue repeating this division until the number in front of the remainder is only zero. 5. The answer is the remainders read from the bottom up.

510 = 1012

(a binary conversion)

Example 2: Convert 14010 to base 8.


The process is the same as in example 1. The answer is:

14010 = 2148
(an octal conversion)

Example 3: Convert 11010 to base 16.


The process remains the same. BUT there is one problem in base 16 that did not appear in the examples above. One of the remainders in this division contains 2 digits (14). You CANNOT allow 2 digits to reside in one of the place holdings in a number. For this reason, base 16, which can have six 2-digit remainders (10, 11, 12, 13, 14, 15) replaces these values with alphabetic representations (10A, 11-B, 12-C, 13-D, 14-E, 15-F). The answer is:

11010 = 6E16
(a hexadecimal conversion)

Change a number from any base back to base 10:


The computer is representing a number from the keyboard by a pattern of ON and OFF signals represented by 1011. What number was typed at the keyboard to produce this pattern? Let's see how we can quickly convert numbers back to base 10 so that they will have more meaning to us humans.

Example 1: Convert 2358 into base 10.


The Process:
Above each of the digits in your number, list the power of the base that the digit represents. See the example on the left. It is now a simple process of multiplication and addition to determine your base 10 number. In this example you have Now simply add these values together. 0

5x8 =5 3 x 81 = 24 2 x 82 = 128

5 + 24 + 128 = 157 Answer: 2358 = 15710

**Remember: any number to the zero power equals one.

Example 2: Let's do the problem at the top of this lesson. Convert 10112 to base 10.
The process is the same as in example 1.

1 x 20 = 1 1 x 21 = 2 0 x 22 = 0 1 x 23 = 8

1 + 2 + 0 + 8 = 11 Answer: 10112 = 1110

Example 3: Convert 1C416 to base 10.


4 x 160 = 4 C x 161 = 12 x 161 = 192 1 x 162 = 256 4 + 192 + 256 = 452 Answer: 1C416 = 45210

Convert a number from any base to any other base:


When converting from any number base to any other number base, and neither of the bases is base 10, you must go via (through) base 10.

Example: Convert 248 into base 2.


Convert 248 into base 10.

4 x 80 = 4 2 x 81 = 16

And then convert that answer into base 2.

4 + 16 = 20 248 = 2010

2010 = 101002 Answer: 248 = 101002


Lessons:

Open the Software: Create a New Project Write Your Program After Typing Your Source Code Opening an Existing Program Close a Program

Remember: You will need to Download the AP Classes into your include folder, as well as the header file SCREEN.H.

Open the Software: Create a New Project

Refer to your tri-fold brochure, Microsoft Visual C++ Quick Reference Guide, as you read through this page for the first time.
Microsoft Visual C++ 6.0 is a powerful, sophisticated software package. It can be used by a novice or by a professional designing sophisticated Windows applications. In this introductory course, we will only be using a small portion of the capabilities of this software package. Let's get started!

Open the Software ( MS Visual C++) (If you are working on a networked system, you
will need to login to your system and then access MS Visual C++.) If you are working in a PC environment: 1. Open Start Menu 2. Select Programs 3. Select MS Visual C++ 6.0 When the Tip of the Day dialog box appears, close it by clicking on the Close button. If you do not want to see the Tip of the Day every time you open Visual C++, click the Show tips at Startup check box to remove the check mark and deselect this feature.

Create a New Project (refer to your tri-fold brochure)


Microsoft Visual C++ offers an easy-to-use GUI, graphical user interface. It contains a Project Workspace window, an Editor window (where you will write your programming code), and an Output Message window (where you will see your error messages). 1. Pull down FILE menu 2. Select NEW

Visual C++ organizes programming tasks into projects. EVERY program that you write MUST be placed within a project before it can be compiled and executed. 3. Select PROJECT tab 4. Select Win32 Console Application 5. Enter a project name 6. Click OK

** Be very careful NOT to select "Win32 Application" by mistake as this will cause
BIG problems for your programs in this course.

7. Select Empty Project 9. Click OK 8. Click Finish Good job!! You have just set up your project. Now let's move on to writing programs.

Write Your Program

Refer to your tri-fold brochure, Microsoft Visual C++ Quick Reference Guide, as you read through this page for the first time
Once you have created your project, it is time to start typing the source code for your program. 1. Pull down the FILE menu 2. Select NEW 3. Select the FILE tab 4. Select C++ Source File 5. Enter a file name Your project name and your file name can be the same if you wish. Your source code files will have the extension .cpp 6. Click OK

You will now see the three main windows of MS Visual C++. The Project Workspace (on the left) has two tabs named Class View and File View at the bottom. We will be using the File View tab to determine if all of the needed files are contained within a project.

When you begin typing your source code you will notice that different words will appear in different colors. This feature will help you distinguish between such items as reserved coding words and comments.

OR ... to Write Your Program you may ....


... click the NEW TEXT FILE icon on the toolbar (far left). If you use this icon, save immediately to engage the color coding when writing your program. Then select Project, then Add to Project, and Files from the main menu. Name the program something.cpp. Type code.

After Typing Your Source Code


Refer to your tri-fold brochure, Microsoft Visual C++ Quick Reference Guide, as you read through this page for the first time
Once you have typed your source code, it is time to save your work and see if your program works properly.

1. Pull down FILE menu, select SAVE 2. Pull down BUILD menu, select BUILD project.exe

- or use the save icon - or press F7, or choose the build icon

3. If an error message occurs, double click on the error message to get an arrow pointing to the spot in the program source code that caused the error. 4. Pull down the BUILD menu and select EXECUTE project.exe - or use execute icon

5. Press ALT and ENTER to see your display in a full black screen. 6. Press any key to close the black screen. Do NOT click the mouse on the underlying screen
to close the black screen.

Open an Existing Program


Refer to your tri-fold brochure, Microsoft Visual C++ Quick Reference Guide, as you read through this page for the first time
If you cannot finish typing your program in one sitting, you will need to save the program and return to it at another time. Let's see how to open a program that has already been written and is stored on the computer.

A project workspace (the left side) must always be open when you are working.

1. Pull down FILE menu 2. Select OPEN WORKSPACE 3. Double click to open project folder. 4. Double click on project.dsw If your code does not appear in the editor window at this time: 5. Pull down the FILE menu 6. Select OPEN 7. Select your program.cpp

Choosing only FILE/OPEN, will cause a prompt box to appear when you attempt to execute the program. Do not create a default workspace. Click NO and return to step 1 above.

Close a Program
Refer to your tri-fold brochure, Microsoft Visual C++ Quick Reference Guide, as you read through this page for the first time
You have finished working and you need to close the program and exit the software package.

1. Pull down the FILE menu 2. Select CLOSE WORKSPACE to close the entire screen. 3. Answer YES to the dialog box. 4. Pull down the FILE menu and select EXIT to leave the software package.

Choosing CLOSE only, will close only the program and not the project.

Is storage space a problem on your computer?


When you BUILD and EXECUTE a project, a large number of files are created. If you are experiencing a shortage of storage space, you may wish to delete some files. The only files that are crucial and must remain in storage are files with the extension .cpp (program code), .h (header files), and .mdp and .mak (files that organize a project). All other files will be recreated again by compiling, linking, and executing your program.

The Mechanics of Creating a C++ Program

Editor: accepts the typing of the


source code (or header file). Source file: the file that contains the program you prepared in the editor after you save it. (.cpp) Header file: header files such as iostream.h Preprocessor: performs preliminary operations on files before they are passed to the compiler. Compiler: translates the source code to machine language. Object code: the file containing the translated source code. (.obj) Linker: links the object file with additional code, such as the library codes. Executable code: the file containing the final product. (.exe)

Command Words (Keywords) for Visual C++


Here are the primary Visual C++ command words (or keywords or reserved words). These words ALWAYS appear in lowercase. You should not give functions or variables the same name as any of these keywords. asm case const delete else export float if mutable auto catch const_cast do enum extern for inline namespace bool char continue double except false friend int new break class default dynamic_cast explicit finally goto long operator

private reinterpret_cast sizeof switch true typename virtual while

protected return static template try union void

public short static_cast this typedef unsigned volatile

register signed struct throw typeid using wchar_t

Output to the Screen


cout (pronounced "see-out") is not a Visual C++ command word, although it acts like
one. You will not see cout in the list of Command Words (or Keywords). cout is an operator (just as addition or multiplication are operators) described in the header file iostream.h. cout sends output to an output device, usually the screen. The double arrows (<<) point the way (toward "out"), showing that the information is going "out" to the monitor.

The following is a table of escape Sequence \n \b \t \a \\ \' \" \? Name New line Backspace Horizontal tab Alert Backslash Single quote Double quote Question mark

sequences which can be used with cout:


Meaning Moves to beginning of next line Backs up one character Moves to next tab position Sounds a beep Displays an actual backslash Displays an actual single quote Displays an actual double quote Displays an actual question mark

If you wish to use the ANSI code sheet to print "fancy" characters on the screen, you can place the code sheet's octal number after a backslash with a cout statement. For example,

cout << "\3" ;

//prints a small heart on the screen.

If you wish to use the ASCII code sheet to print "fancy" characters on the screen, use the following syntax:

cout<< char(228);

// prints the Greek letter sigma on the screen.

Tidbits of information about those pesky tabs:


1. printing in the last column will force a new line. 2. the tab spacing is every 8 columns consistently starting with 1: (9, 17, 25, 33, 41, 49, 57, 65, 73 . . . then go to 1) 3. tabbing beyond one line's "worth" will push the tabs into the same tabbing pattern on the next line starting with 1. 4. tabbing takes you to the next available tab. 5. if you print in the "8th" column and then tab, tab will skip the next field and take you to the NEXT tab location. 6. tabbing without the use of \n, will simply continue in the same pattern.

Clearing the Screen, Flush, and Pause Clearing the Screen:


system("CLS");
The standard library header file <stdlib.h> is needed.

system("CLS");

When the screen is cleared in Visual C++, the cursor is moved to the upper left corner of the screen. To clear the screen in Visual C++, utilize the code:

Note: If you wish to clear the screen after a cout statement, you will need to
"flush" the iostream. system ("CLS"); cout<< "Hello"<<flush; //flush forces the printing to the screen before it clears system ("CLS"); cout<< "Good-Bye"<<endl;

Flushing the Output Stream:


You will discover that it will be necessary on occasions to "clear the output stream". All information going "out" to the screen goes through the output stream. (Thus the header named <iostream.h> - input/output stream.) To force the information to go to the screen immediately (and not wait for more information to enter the stream before outputting to the screen), we will be using flush. The correct syntax will be:

cout << "Flushing the output stream." << flush; If you are using a clear screen command (system ("CLS");) in the middle of a program and it does not appear to be working ... flush the cout statements which precede the clear screen command.

Pausing the screen until user hits a key:


system("PAUSE");
Note: This command will "pause" the screen and display the message "Press any
key to continue . . . " as it waits for a keystroke. If you wish to pause the screen after a cout statement, you will need to "flush" the iostream. (Requires header file <stdlib.h>) cout<< "Hello"<<endl<<flush; //flush forces the printing to the screen before it pauses system ("PAUSE"); //pause displays a message and waits for the user to hit a key cout<< "Good-Bye"<<endl;

Example:
//This program will clear the screen and print a message. #include <iostream.h> #include <stdlib.h> int main(void) { system ("CLS");

cout << "\tHi, there!\n\n"; cout << "\nComputers are"; cout << "great!\n"; return 0; }
Let's see what the output from this program will look like. The screen display is shown in the table below. The cells of the table are used to represent the coordinates of the screen. Refer to your grid sheet. 1 2 3 4 5 6 7 8 9 H 10 11 i , 12 13 t 14 h 15 e 16 r 17 e 18 ! 19

Of course, there are more than 19 columns across your screen (there are 80). Notice the following things:

the placement of the word Hi in the 9th column after the \t (tab) was executed. the number of lines that were skipped in relation to the number of \n commands. the lack of any empty spacing between the word are and great.

ANSI/ASCII Charts
ANSI - American National Standards Institute ASCII - American Standard Code for Information Interchange

Remember how to use each chart:


To use the ANSI chart: cout << "\44"; //prints $ To use the ASCII chart: cout << char(36); //prints $ You may utilize whichever chart you prefer.

Demo 1: Parts of a C++ Program


// Comments at the beginning: // your name // a description of the program // information pertinent to the program #include <iostream.h>

#include <stdlib.h> int main(void) { system ("CLS"); cout<< "This is a literal print.\n"; cout<< "Yea!"<<endl; return 0; }

The CODE:
// Comments at the beginning: // your name // a description of the program // information pertinent to the program

Information about the code:


All programs should begin with a comment identifying the programmer and the purpose of the program. Preprocessor directives begin with # and tell the computer to find the filename that follows and read it in. The file iostream.h (Input/Output stream) is used by cout. The stdlib.h is used to clear the screen. Note: <iostream.h> should always be your first "header" file. This code begins the actual program. EVERY C++ program has a main( ) function. A function is a block of code that performs one or more actions. While functions are usually called within a program, main( ) is called automatically. You may see various adaptations of this line of code. While other adaptations are allowed, be sure to maintain "int" as the return type because every ANSI-compliant C++ program will return zero to the IDE. Between the French curly braces is the body of function main( ). It is indented and terminates by returning 0 to the IDE. This body: * clears the screen, * prints This is a literal print. Yea! to the screen.

#include <iostream.h> #include <stdlib.h>

int main(void)

{ system ("CLS"); cout<< "This is a literal print.\n"; cout<< "Yea!"<<endl; return 0; }

Demo 2: Demo of comments


//************************************ // Name: William Ryker // Assignment: Unit 1 #2 // The "Hi" program // Date: Stardate 2504 //************************************ #include <iostream.h> int main(void) { cout<< Hi!;

// message to user

return 0; //terminate main and return integer 0 } /* this older style of commenting allows a comment to wrap around the screen until the terminating symbol is typed. */

The CODE:
//************************************ // Name: William Ryker // Assignment: Unit 1 #2 // The "Hi" program // Date: Stardate 2504 //************************************ int main(void) { cout<< Hi!; 0 }

Information about the code:


All programs should begin with a comment identifying the programmer and the purpose of the program.

// message to user

return 0; //terminate main and return integer

Comments can also be placed within the body of a program to act as documentation. These comments should be brief and to the point. This body prints Hi! on the screen.

/* this older style of commenting allows a comment to wrap around the screen until the terminating symbol is typed. */

This "older" form of commenting which was developed for the C language, is used by C++ programmers to display lengthy comments that wrap around the screen.

Demo 3: Demo of cout<<


//************************************ // Name: Kate Janeway // Assignment: Unit 1 #3 // A Print Investigation program // Date: Stardate 2506 //************************************ #include <iostream.h> #include <stdlib.h> int main(void) { system ("CLS"); cout<< Welcome to the bridge!\n; cout<< "Did you notice that backslash n was inside the quotes?" <<endl; cout<< "Did you notice that endl was outside the quotes?" <<endl; cout<< "Watch out for lines"; cout<< "that continue from the previous line."<<endl; cout<<"Did you notice NO space between \"lines\" and \"that\"?\n"; cout<< "Some\t\t\tImportant\t\t\tMoves\n"; return 0; }

Screen Display
Welcome to the bridge! Did you notice that backslash n was inside the quotes? Did you notice that endl was outside the quotes? Watch out for linesthat continue from the previous line. Did you notice NO space between "lines" and "that"? Some Important Moves
(spacing not exact for the tabs)

Directions: Choose the best answer. Use the button at the bottom to check your answers. 1. Translates and executes a program line by line. [a] compiler [b] interpreter [c] linker [d] control unit

2. Formed on a diskette (or hard drive) during initialization. [a] source code [b] images [c] sectors [d] storage units

3. Several computers linked to a server to share programs and storage space. [a] library [b] grouping [c] network [d] integrated system

4. The physical components of a computer system. [a] control unit [b] hardware [c] software [d] ALU

5. Source code in C++ will not run if it is not indented. [a] true [b] false

6. RAM stands for _________. [a] Read Anytime Memory [b] Read Allocated Memory [c] Random Access Memory

[d] Random Allocated Memory

7. Programs that tell a computer what to do. [a] harware [b] software [c] hard copy [d] projects

8. To prepare a diskette (or hard drive) to receive information. [a] format [b] track [c] interpret [d] boot

9. The CPU consists of: [a] Control Unit, Temporary Memory, Output [b] Control Unit, Arithmetic Logic Unit, Temporary Memory [c] Input, Process, Storage, Output [d] Input, Control Unit, Arithmetic Logic Unit, Output

10. Our decimal number 44, when represented in binary, is: [a] 101100 [b] 101010 [c] 111000 [d] 10100

11. A binary digit (1 or 0) signifying "on" or "off". [a] bit [b] byte [c] megabyte [d] gigabyte

12. Output printed on paper. [a] softcopy

[b] hardcopy [c] source code [d] software

13. The four equipment functions of a computer system. [a] Input, Process, Control Unit, Output [b] Input, Control Unit, Arithmetic Logic Unit, Output [c] Input, Process, Storage, Output [d] Input, Process, Library Linking, Output

14. OOP stands for: [a] Observable Object Programming [b] Object Observed Procedures [c] Object Oriented Programming [d] Object Overloading Practices

15. Equals 8 bits. [a] megabyte [b] gigabyte [c] sector [d] byte
Answer: 1. A 2. C 3. C 4. B 5. B 6. C 7. B 8. A 9. B

10.A 11.A 12.B 13.C 14.C 15.D

Variables and Constants Important Terms:


A variable is a named memory location which temporarily stores data that can change while the program is running. A constant is a named memory location which temporarily stores data that remains the same throughout the execution of the program. The type of a variable indicates what kind of value it will store. The name of a variable is known as its identifier. A variable can be given a value through an assignment statement. C++ recognizes eleven built-in data types which are designated by reserved words: char short float long double unsigned int int long double unsigned char unsigned short

unsigned long Variables of different types occupy different amounts of memory space and are described as having different sizes. ** The basic C++ types that are included in the AP Computer Science subset are int, double, bool and char.

Variables Most Often Used


Data C++ Type Keyword Character char Short short integer Integer Long Integer Float Double Boolean int long float double bool Stores 1 character Integers Integers Integers Decimal values to 7 decimal digit precision Decimal values to 15 decimal digit precision Boolean (Logical) values Bytes of Memory 1 2 4 4 4 8 Range of Values 1 character -32,768 to 32,767 -2,147,483,648 to 2,147,483,647 -2,147,483,648 to 2,147,483,647 3.4e-38 to 3.4e38 positive and negative 1.7e-308 to 1.73e308 positive and negative True or False

Rules for assigning variables:


Assign short, int or long data types when you are sure a variable is an integer number (NO decimal points). While these three integer choices are available, based upon the size of the numbers you are using, we will be using only int. Assign float or double when decimals are needed. We will primarily be using double, as suggested by the AP Computer Science subset.

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

Naming Rules for Variables


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

Rules for naming variables:


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

Samples of acceptable variable names: Grade GradeOnTest Grade_On_Test

Samples of unacceptable variable names: Grade(Test) GradeTest#1 3rd_Test_Grade

Declaring Variables
All variables must be declared before they can be used.

How to declare a variable:


1. Choose the "type" you need. 2. Decide upon a name for the variable. 3. Use the following format for a declaration statement: datatype variable identifier; 4. You may declare more than one variable of the same type by separating the variable names with commas. int age, weight, height; 5. You can initialize a variable (place a value into the variable location) in a declaration statement. double mass = 3.45; Variables that are not initialized are NOT empty. If you do not initialize your variables, they will contain junk ("garbage") values left over from the program that last used the memory they occupy, until such time as the program places a value at that memory location.

Constant Variables

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

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

Placing Data in Variables

The equal sign (=) is used for assigning values to variables. The format of an assignment is: variable = expression; The variable is a variable name that you defined in the program. The expression is any variable, numerical, literal, or expression that produces a data type that is the same as the variable's data type. Data may be placed in a variable when it is declared: int grade = 98; or data may be placed in a variable AFTER it has been declared (at a point further down in the program): int grade;

... grade = 98;

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

Are computers and mathematicians always speaking the same language?


A computer does not interpret an equal sign in the same manner that mathematicians do. To a computer, the equal sign means that you want to take the number, variable, or expression on the right side of the equal sign and put it into the variable on the left. A computer understands: grade = 98; but a computer does not understand 98 = grade;

The statement x = x + y; may look mathematically incorrect, but to a computer it means "take what was stored in x, add y to that value, and place the answer back in x". Remember that what is on the right side will be STORED in the variable on the left.

Mathematician:

Computer:

i=i+1
"NO way!!" "Way cool!!"

Answer:

While they agree on concepts, they do not necessarily agree on syntax (the manner in which the concepts are expressed).

Compound Operators:
C++ has its own shortcut syntax involving the placement of values into numerical variables. You should be able to recognize all possible codings. x += y; x -= y; x *= y; x /= y; x %= y; is the same as is the same as is the same as is the same as is the same as x = x + y; x = x - y; x = x * y; x = x / y; x = x % y;

While a powerful tool used to update variables, compound operators can be troublesome. In the order of operations, the compound operators have lower precedence than regular math operators. Check out these two examples:
int x = 42; int value = 0; value = value - x + 2; cout<< value; //gives - 40 int x = 42; int value = 0; value -= x + 2; cout<<value; //gives - 44

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

Primary Math Operators

+ * /

Addition Subtraction Multiplication Division

% Modulus (also called remainder) Did you notice that there is no symbol for "exponent"?

The MODULUS Operator %


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

22 % 6 = 4

because 22 / 6 = 3 with a remainder of 4

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

Confusing DIVISIONS
When dividing an integer by an integer, the answer will be an integer (not rounded). Compare these divisions: (5 is an integer while 5.0 is a double) Integer division Double division Mixed division 8/5=1 8.0 / 5.0 = 1.6 8.0 / 5 = 1.6

Be careful when performing integer division.

When an operation involves two types (as the mixed division

shown above), the smaller type is converted to the larger type. In the case above, the integer 5 was converted to a double type before the division occurred.

Printing Variables
The cout statement may be used to print the information stored in any variable location to the screen. It is possible to intermix several types of variables into one cout statement as seen below: int num1 = 4; double num2 = 6.5; cout << num1 << " and also " << num2 << endl; or for easier reading: cout << num1 << " and also " << num2 << endl;

Numbers and/or computations may also be printed without variable names: cout << 976; // prints 976 on screen cout << 3*5*2+10; // prints 40 on screen

Formatting Output

The manipulators discussed on this page require the header file named iomanip.h #include <iostream.h>

#include <iomanip.h>
Formatting output is important in the development of output screens which can be easily read and understood. C++ offers the programmer several input/output manipulators. Two of these I/O manipulators are setw( ) and setprecision( ).

The setw( ) manipulator sets the width of the field


assigned for the output. It takes the size of the field (in number of characters) as a parameter. For example, the code: cout << setw(6) <<"R"; generates the following output on the screen (each underscore represents a blank space) _ _ _ _ _R The setw( ) manipulator does not stick from one cout statement to the next. For example, if you want to right-justify three numbers within an 8-space field, you will need to repeat setw( ) for each value: cout << setw(8) << 22 << "\n"; cout << setw(8) << 4444 << "\n"; cout << setw(8) << 666666 << endl; The output will be (each underscore represents a blank space) ______22 ____4444 __666666

The setprecision( ) manipulator sets the total


number of digits to be displayed when floating point numbers are printed. For example, the code: cout << setprecision(5) << 123.456; will print the following output to the screen (notice the rounding):

123.46 The setprecision( ) manipulator can also be used to set the number of decimal places to be displayed. In order for setprecision( ) to accomplish this task, you will have to set an ios flag. The flag is set with the following statement: cout.setf(ios::fixed); Once the flag has been set, the number you pass to setprecision( ) is the number of decimal places you want displayed. The following code: cout.setf(ios::fixed); cout << setprecision(5) << 12.345678; generates the following output on the screen (notice no rounding): 12.34567

Additional IOS flags:


In the statement: cout.setf(ios::fixed); "fixed" is referred to as a format option.
Other possible format options:

left right showpoint uppercase showpos scientific fixed

left-justify the output right-justify the output display decimal point and trailing zeros for all floating point numbers, even if the decimal places are not needed. display the "e" in E-notation as "E" rather than "e" display a leading plus sign before positive values display floating point numbers in scientific ("E") notation display floating point numbers in normal notation - no trailing zeroes and no scientific notation

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

Displaying Amounts of Money:

To get 5.8 to display as 5.80, the following lines of code are needed"
//display money cout.setf(ios::fixed); cout.setf(ios::showpoint); cout << setprecision(2); cout << 5.8; All subsequent couts retain the precision set with the last setprecision( ). Setprecision( ) is "sticky." Whatever precision you set, sticks with the cout device until such time as you change it with an additional setprecision( ) later in the program.

Using cin >>


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

Sample program:
// sample program for cin #include <iostream.h> int main(void) { int fleas; cout << "How many fleas does your cat have?"; cin >> fleas; cout << "Well, that's " << fleas << " fleas too many!! \n\n\n"; return 0; }

cin can accept more than one variable as follows:

cout << "Enter an integer and a decimal:"; cin >> integer >> decimal; You would enter the values by typing on a single line and leaving a space between them, or by typing them on separate lines and hitting ENTER after each entry.

Character Literals and Variables


Characters are always only ONE letter or ONE character. Character literals always appear inside single quotation marks. Define char variables for character data. // Example of character literals #include <iostream.h> int main(void) { char first, middle, last; first = 'D; middle = 'O'; last = 'G'; // Rest of program would follow

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

Strings

String Literals
A string literal is any alphanumeric enclosed in double quotation marks. All string literals end with a string-terminating zero (NULL). Visual C++ uses this stringterminating zero to determine the end of a string value. Notice how the string literal "Dogs Rule!" would be represented:

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

\0

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

String
"R" "5" "Wally" "" "My Computer"

Length
1 1 5 0 11

Character literals ALWAYS have a length of one. There is no null zero terminator for character literals. The letter 'R' as a character in memory: The letter "R" as a string in memory: R R \0

Storing Strings in Arrays


There are NO string variable types in the Standard C++ language. Instead, strings are stored in character arrays. Think of an array as a big "box" subdivided into compartments. Each compartment in the array will hold the same type of variable. You may have worked with arrays (vectors/matrices) in mathematics. A character array can hold one or more character variables in a row in memory. char dogName[10]; //dogName holds a string

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

W
[0]

a
[1]

l
[2]

l
[3]

y
[4] [5]

D
[6]

o
[7]

g
[8]

\0
[9]

NOTE: The elements of the array are subscripted, starting with the number zero. NOTE: Be sure to make the array size large enough to hold the string AND its nullterminating character (\0). (There are 10 boxes needed to hold "Wally Dog".)

NOTE: Never try to assign string values to character arrays using a regular
assignment statement, except when you first declare the character array. dogName[10] = "Wally Dog"; //WON'T WORK!!!!!!!!!!!

AP Classes and String Variables


(Download these classes, if you have not already done so.) The Advanced Placement Computer Science (APCS) Committee is the committee responsible for creating the APCS Examination. They have created a variety of C++ tools, based on the C++ standard, for the beginning programmer. One such tool, features the creation of an apstring data type. The letters "ap" associated with these tools let you know

that they are not part of your current C++ compiler, but were developed by the APCS Committee. The AP* tool needed to use this new string variable is apstring.cpp, and this new variable is declared as being of type apstring. Using the type apstring is similar to using int, double, and char. You must use #include "apstring.cpp" to have access to this special apstring data type. You must install the AP Classes in the "include" directory of your software before using them. A link to the AP Classes can be found on the C++ main (opening) page. //sample program #include <iostream.h> #include "apstring.cpp" int main(void) { apstring CrewName; CrewName = "Neelix"; return 0; }

//declare variable //initialize variable

The use of the apstring class will eliminate all of the problems of dealing with character string arrays that we have seen. With the apstring class we can initialize string variables whenever and wherever we wish and the computer will automatically keep track of the length of the string.
AP* is a registered trademark of the College Entrance Examination Board, which was not involved in the production of this web site.

More Than You Wanted to Know About Floating Point Variables


"Why do I tend to get warnings when I declare float variables?"
Visual C++ defaults all floating point numbers to doubles. Since doubles are "larger" (or "smaller") than floats and require 8 bytes (floats require 4 bytes), the program is most likely thinking that you are casting - forcing a variable to take on the properties of

another type. It is trying to warn you that your "double" may lose some of its accuracy if changed to a smaller ranged type, such as a float. Just remember: To Visual C++, any number with a decimal point is a double. Since the Advanced Placement Examination deals primarily with doubles, we also will concentrate on the use of doubles.

Floating point variables involved with integer division are often confusing. Consider the following situation:
int slices; //representing slices of pizza at 375 calories per slice float miles; //representing miles needed to jog off the pizza calories miles = (375 * slices / 100): 1. If you declare slices as an int, and use miles = (375 * slices / 100); you have integer division taking place on the right hand side, since 375 and 100 are ints. This integer calculation is completed and the result is placed into a float. You get a warning of possible loss of data due to the integer division (in this case). You get the WRONG ANSWER displayed. 2. If you declare slices as an int, and cast the right hand side miles = float(375*slices/100); you are forcing the machine to accept the value of the parenthesis as a float type. But the parenthesis is computed first and the integer division occurs. Now, there is no warning, but the WRONG ANSWER is displayed. 3. If you declare slices as a float, you have prevented "integer division" from occurring and the CORRECT ANSWER is displayed. 4. Suggestion: ALWAYS BE AWARE OF INTEGER DIVISION - AND AVOID IT! In this case, declare int slices, and double miles. Make the computation line miles = (375.0*slices/100); The simple addition of the .0 makes 375.0 a double and solves all of the problems of integer division occurring. Clear as muddy water, isn't it!!! :- )

Demo Working with Variables


Sample program:
(TASK: Write a program to fill 2 integer variables with the number of 17 year old girls and boys in the class, establish a constant age variable = 17, and perform multiplication of the constant times the variables producing the total number of years. All of the students in the class are 17 years old.)
#include <iostream.h> int main(void) { int girls = 15; int boys = 19; const int age = 17; //cannot be changed or reassigned within this program cout<< "Total number of years will be "<<age*girls<<" and "<<age*boys<<"."; cout<<endl<<endl<<endl; return 0; }

Screen Display
Total number of years will be 255 and 323.

Demo Division and Modulus


Sample program:
(TASK: Write a program that will group horses into available pastures. Start by putting an equal number of horses in each pasture. Indicate how many horses will not be placed in a pasture by this process. There are always more horses than pastures for this problem.)
#include <iostream.h> int main(void) { int horses, pastures, horsesInEachPasture; int leftOver; cout<<"How many horses are on the farm? ";

cin>>horses; cout<<"How many pastures are available on the farm? "; cin>>pastures; //compute the number of horses per pasture horsesInEachPasture=horses/pastures; //integer division cout<<"\nThere will be "<<horsesInEachPasture<<" horses per pasture.\n"; //compute the number of left over horses using modulus leftOver = horses%pastures; cout<<"There will be "<<leftOver<<" horses without a pasture in this process.\n"; return 0; }

Screen Display:
How many horses are on the farm? 10 How many pastures are available on the farm? 3 There will be 3 horses per pasture. There will be 1 horses without a pasture in this process.

Demo Standard Character String Arrays


Sample program:
(This program shows how to use standard C++ character string arrays. Notice the limitations placed upon their manipulation. The AP Class apstring will allow us to deal more efficiently with such string data.)

#include <iostream.h> int main(void) { //assigning strings to character arrays with = sign must be done in the //declaration statement! char animalOne[6] = "Lions"; //reserves cells for 5 letters and the null character char animalTwo[ ] = "tigers"; //lets the computer do the counting!! char animalThree[ ] = "bears"; cout<<animalOne<<" and "; //notice no brackets needed to print array cout<<animalTwo<<" and "<<endl; cout<<animalThree[0]<<endl //to print array one cell at a time, use subscripts <<animalThree[1]<<endl //one at a time. <<animalThree[2]<<endl <<animalThree[3]<<endl <<animalThree[4]; //to change the word "Lions" to "dogs", you must change ONE letter at a time. animalOne[0]='d'; animalOne[1]='o'; animalOne[2]='g'; animalOne[3]='s'; animalOne[4]=' '; cout<<endl<<animalOne; cout<<"\n\aOh my!! cout<<endl<<endl<<endl; return 0; } :-0";

Screen Display:
Lions and tigers and b e a

r s dogs Oh my!!

:-0

Demo Program with Pseudocode


In the past, programmers would develop flowcharts to outline the structure of a program. Today, more programmers utilize the process of pseudocoding. Pseudocode is an outline of how a program will be developed written in both English and C++ syntax. During the pseudocode process, decisions are made as to the variable names that will be used and any formulas that the program may require.

Sample program using pseudocode:


(TASK: Write a program that will ask a student to enter his/her first name, 2 report card grades for CS1, and final examination score. The program will then print out the student's course grade based upon the fact that the 2 quarter grades will count twice and the final examination will count once). Pseudocode:
1. 2. 3. 4. Ask for name (apstring name) Ask for quarter grades (int G1, G2) Ask for final exam (int final) Compute the course grade (double grade = (2*G1 + 2*G2 + final)/5) 5. Print information to screen

Directions: Choose the best answer. Use the button at the bottom to check your answers. 1. When working with character arrays, always reserve enough array elements to hold the string AND its null-terminating character (\0). [a] True [b] False

2. In C++, 14 % 4 = [a] 1 [b] 2 [c] 3 [d] 4

3. Variables that are declared, but not initialized, contain [a] blank spaces [b] zeros [c] "garbage" values [d] nothing - they are empty

4. Array indexing always starts with the number [a] 0 [b] 1 [c] 2 [d] \0

5. A character variable may contain up to seven letters. [a] True [b] False

6. All strings end with a null zero in memory. [a] True [b] False

7. In C++. 5 / 2 = [a] 2 [b] 2.5 [c] 3 [d] none of the above

8. Variables with names that describe the data stored at that particular memory location are called [a] identifiers [b] constant variables [c] floating point variables [d] mnemonic variables

9. The name of a variable is known as its [a] identifier [b] constant [c] data type [d] base

10. The special class developed by the College Board to be used with strings is [a] apstrings.cpp [b] apstring.cpp [c] aparray.cpp [d] apletters.cpp

11. In C++, the % refers to [a] percentages [b] modulus operator [c] division [d] data storage

12. A variable is given a value through [a] osmosis [b] the cout statement

[c] the <iomanip.h> header file [d] an assignment statement

13. Variable names may begin with a number. [a] True [b] False

14. When a data type must contain decimal numbers, assign the type [a] int [b] char [c] double [d] long int

15. Mathematicians and computers interpret the equal sign (=) in the same way. [a] True [b] False

16. setprecision requires the header file [a] stdlib.h [b] iomanip.h [c] console.h [d] conio.h

17. The following statement is valid. [a] True [b] False

double price = 7,450.98;

18. All variables must be declared before they can be used. [a] True [b] False

19. Character literals always have a length of one. [a] True

[b] False

20. If char catname[15]; , which of the following is valid? [a] catname[15] = "Millie"; [b] catname = "Millie"; [c] catname[ ] = "Millie"; [d] none are valid

1. A 2. B 3. C 4. A 5. B 6. A 7. A 8. D 9. A 10.B 11.B 12.D 13.B 14.C 15.B 16.B 17.B 18.A 19.A 20.D

the APSTRING class


21.

From the College Board for Advanced Placement Computer Science

Remember:

A string is a sequence of multiple characters, such as words, sentences, or addresses. They are referred to as alphanumerics (alphabet characters and/or numbers). As we have already discovered, there is no built-in string data type in standard C++. We created "strings" by using an array of characters, such as char name[ ] = "Alexis";

A
0

l
1

e
2

x
3

i
4

s
5

\0
6

We quickly discovered that these "strings" were difficult to manipulate - such as the difficulties associated with assigning new values. The College Board has allowed for the inclusion of the APSTRING class to allow for easier manipulation of "strings". There are two necessary components to using the APSTRING class:

"apstring.h" "apstring.cpp"

- library (commented) header file for new manipulation functions - implementation header file. It uses #include <string.h>, #include <assert.h>, and #include "apstring.h"

using APSTRING class

The APSTRING class is used to implement an additional data type (variable) called apstring, to declare string variables. Programs using this class must utilize:

#include "apstring.cpp"
to declare a string variable called name: to assign a value to a string variable: to input a single word to a string variable:
(cannot be used to enter a string containing spaces) (reads until '\n' (carriage return) is detected) ('\n' is NOT stored in the string variable) (PROBLEM: does not ignore leading whitespace)

apstring name; name = "Jessie"; cin >> name;

to input more than one word to a string variable: getline(cin, name);

to print a string variable: to print a specific character of a string variable: to compare 2 strings:
(comparisons can be made with the operators ! =, = =, <, >, < =, > = The < and > operators allow for alphabetic comparisons.)

cout << name; cout << name[2]; if (name = = "Alexis") if (name1 < = name2) name = ""; (no space)

to create an empty string:

Member functions of the apstring class


length( )
- returns the number of characters contained within the string. - does not include the null character at the end of the string. - largest string length is 1024. example: apstring name = "Alexis"; cout<< name.length( ); // will display 6

substr(x, y)

- returns the part of the string that starts at position x and is y characters long. - remember that array subscripts begin at zero. example: apstring word = "reaction"; cout<<word.substr(2,3); // will display act

find(somestring)

- returns the position (number) of the first occurrence of somestring in the string. example: apstring name = "Frederick"; cout<<name.find("red"); // will display 1

find(somechar)

- returns the position (number) of the first occurrence of somechar in your string. example: apstring word = "roadrunner"; cout<<word.find('e'); // will display 8

c_str( )

- returns a C-style (not C++) string needed when using strings with functions from other libraries. example: apstring number; cout<< "Please enter one integer "; cin >> number; cout<< number << " times three will be "<< 3 * atoi(number.c_str( ) );

Operator member functions of apstring class


Concatenation puts two strings together so that the second string follows

immediately after the first string. When used with numbers, + means add, but when used with strings, + means concatenate. example: apstring firstword = "apple"; apstring secondword = "fritter"; cout<< firstword + secondword; //will show applefritter

It is possible to concatenate one string onto the end of another string.

Remember:

x += y means x = x + y.

example: apstring firstword = "Wally"; apstring secondword = "Dog"; apstring newword = " "; newword += firstword; newword += " "; newword += secondword; cout<<newword; // will display Wally Dog

Problems with getline(cin, name);


Since getline does not ignore leading whitespace characters, you should take special care when using it in conjunction with cin >>.

The problem:

cin>> leaves the newline character (\n) in the iostream. If getline is used after cin>>, the getline sees this newline character as leading whitespace, thinks it is finished and stops reading any further.

Program fragment with problem:


#include "apstring.cpp" apstring name;

OUTPUT:
Enter your age 5 Enter your full name Ben Bunny

, you are 5

int age; cout<<"Enter your age"; cin>>age; cout<<"Enter your full name"; getline(cin, name); cout<<name<<", you are " <<age<<endl;

The name did not print because the getline saw the newline character left from the cin>> as whitespace and stopped reading any further.

The yellow wave is the iostream. The cin statement uses the 5 and leaves the \n in the stream as garbage. The cin statement will NOT read (or "grab") \n. The cin also ignores \n when reading data. The getline, on the other hand, reads and "grabs" \n. So, when it sees the \n LEFT from cin, it "grabs" the \n and thinks it is finished reading.

Don't be a dumb bunny and fall for this trap!!!

Ways to fix the problem:


Method 1:
Reverse the order of the input. Avoid putting getline after cin >>.
This method has limited applications. If you are looping, this will not solve the problem.

Method 2:
Consume the trailing newline character from the cin>> before calling getline, by "grabbing" it and putting it into a "dummy" variable.

You will see me using this method throughout the course.

apstring dummy; getline(cin, dummy);

or
cin.ignore(100,'\n'); // skips up to 100 characters // stopping after it finds and "grabs" \n

Program fragment with correction:


#include "apstring.cpp" apstring name, dummy; int age; cout<<"Enter your age"; cin>>age; getline(cin,dummy); cout<<"Enter your full name"; getline(cin, name); cout<<name<<", you are " <<age<<endl;

OUTPUT:
Enter your age 5 Enter your full name Ben Bunny Ben Bunny, you are 5

Demo apstring class


//Demo for apstring class #include<iostream.h> #include<stdlib.h> #include "apstring.cpp" //need this for strings int main(void) { system("CLS");

apstring name, animal1, animal2, animal3; cout<<"\t\t\tTHE LIST OF UNUSUAL ANIMAL NAMES\n\n"; cout<<"What is your name? "; getline(cin,name); //allows for full name containing spaces cout<<name<<", this program will allow you to enter 3 animal names"; cout<<"\nPlease enter the first name: "; getline(cin,animal1); cout<<"\nPlease enter the second name: "; getline(cin,animal2); cout<<"\nPlease enter the third name: "; getline(cin,animal3); cout<<"\n\nWow, are those real names!!!"; cout<<endl<<endl<<endl; return 0; }

Relational Operators
Operator Description equal to not equal to greater than greater than or equal to less than less than or equal to

== != > >= < <=

There are six relational operators used for data comparisons in C++. These operators must always appear between 2 literals, 2 variables, 2 arithmetic expressions, or a

combination of these possibilities. The operators may be used with numbers, characters, or apstrings. Check out this example:
Assume these values are assigned: int a = 4; int b = 12; int c = 16; int d = 4; ... then the following are true: a==d b<c c>a c != d a >= 0

Notice that ONE equal sign is used to "assign" a value, but TWO equal signs are used to check to see if values are equal to one another.

Relational operators always yield a TRUE or FALSE result. Remember that a TRUE result evaluates to any non-zero value (often 1), while a FALSE result evaluates only to zero. Relational operators have a lower precedence than the arithmetic operators. This means that an expression such as x + 4 > = y - 5 is the same as (x + 4) > = (y - 5).

The "if" Statement


It's time to make decisions using the relational operators.
The "if" expression is called a conditional statement (decision statement). It tests a relationship by using the relational operators. Based upon the results of these

comparisons, decisions are made as to which statement(s) the program will execute next.

if (test condition) { block of one; or more C++ statements; }


If you put a semicolon after the test condition, the "if" statement will STOP. The block will not be executed.

The test condition can be any relational comparison (or logically TRUE) statement and must be enclosed in parentheses. The block of statements is enclosed in French curly braces and are indented for readability. The braces are NOT required if only ONE statement follows the "if", but it is a good idea to get in the habit of including them. The block executes only if the test condition is TRUE. If the test condition is FALSE, the block is ignored and execution continues to the next statement following the block.

Be careful!!! A careless mistake may go unnoticed.


if (a = 3) is almost ALWAYS true. The condition a = 3 is actually an "assignment statement" (most likely NOT what you really intended to type), and assignments are consider to be true for any value other than 0. If the assignment value is 0, such as if (a = 0), the condition is considered false. whereas: if (a = = 3) is true ONLY if the value stored in a is the number 3. This is most likely what you intended to type.

Examples:
// using a character literal if (grade = = 'A') { cout<<"Put it on the frig!"; } // logically true test condition // when x is a non-zero value the // test condition is considered true if (x) { cout<<"Way to go!"; cout<<"The x is not zero!"; } // using a calculation if (cost * number = = paycheck) { inventory = 0; }

// using two variables if (enemyCount < heroCount) { cout<<"The good guys win!"; }

The "if ... else" Statements


Let's look at situations when the word "otherwise" can be used in your decision making! if (test condition) { block of one; or more C++ statements; } else {

block of one; or more C++ statements; }


If the test condition is TRUE, the block of statements following the "if" executes. If the test condition is FALSE, however, the block of statements following the "else" executes instead.

Example:
//example of if ... else cout<<"Enter the name of your city." getline (cin, city); cout<<"Enter the population"; cin>>population; if (population >= 534187) { cout<<"According to the census, " << city <<" is one of \n the 100 largest cities." } else { cout<<"According to the census, " << city <<"is not one of \n the 100 largest cities." }

The "if ... else if ... else" Statements

Let's look at situations where your program requires more than two situations as the result of a decision. cout<<"Enter a value for a"; cin>>a; cout<<"Enter a value for b"; cin>>b; if(a= = b) { cout<<"They are equal!\n"; } else if( a < b) { cout<<"The first number " << "is smaller.\n"; } else { cout<<"The second number" << is smaller.\n"; }
Notice that it was not necessary to check for a>b in the third situation. The trichotomy principle tells us that numbers are related in one of three ways (a equals b, or a is less than b, or a is greater than b). In order for the computer to get to the "else" condition in the problem above, it must have answered NO to the first two decisions. Consequently, there is only ONE possibility left and we do not waste the computer's time checking it.

Logical Operators
Run your mouse over the panel at the left to see information about the logical operators.

A single comparison in an if statement often is not enough to determine whether data matches your criteria. For example, you may need to check to see if a user enters a number within a certain range. To accomplish this task, you will need the logical operators in your if statement. These logical operators which result in a TRUE/FALSE condition are also referred to as Boolean Operators.

It's time to remember those truth tables from Mathematics! Yeek!! && (AND)
(3 + 2 = 5) && (6 + 2 = 8) TRUE (4 + 3 = 9) && (3 + 3 = 6) FALSE

| | (OR) ! (NOT)

found above the backslash on the keyboard (3 + 6 = 2) || (4 + 1 = 5) TRUE (1 + 1 = 3) || (3 + 3 = 9) FALSE !(4 + 3 = 5) TRUE

BEWARE:
Math: Computer: 2 < x < 10 OK if (2 < x < 10) NO!!!
The computer will only check the first condition 2 < x.

if ((2 < x) && (x < 10)) YES

Remember DeMorgan's Laws:


Mathematical Version: Programming Version:

Equivalent statements: if (!(num >= 0 && num <= 65)) if (num < 0 || num > 65)

Watch Operator Precedence


You can mix logical operators in statements as long as you understand the order in which the logical operators will be applied (precedence).

1. The NOT operator (!) is applied first, 2. then, the AND operator (&&), 3. and finally the OR operator (||).
Consider this example:

dog_acceptable = (tan || black && long-eared)

This example illustrates why it is important to know the order in which logical operators are applied. At first glance it may appear that the statement above would consider a dog to be acceptable if the dog is either tan or black and also long-eared. But in reality, the statement above considers a tan dog with short little ears as an acceptable dog. Remember, the AND operator is evaluated first and then the result of the AND operation is used for the OR operation. The statement can be corrected with parentheses: dog_acceptable = ((tan || black) && long-eared) Now, parentheses are evaluated first.

The "switch" Statement


If your program must select from one of many different actions, the "switch" structure will be more efficient than an "if ..else..." structure.

switch (expression) { case (expression 1):

{ one or more C++ statements; break; }

case (expression 2):

{ one or more C++ statements; break; }

case (expression 3):

{ one or more C++ statements; break; }

. .

. default: { one or more C++ statements; break; }

You MUST use a break statement after each "case" block to keep execution from "falling through" to the remaining case statements. Only integer or character types may be used as control expressions in "switch" statements. It is best to place the most often used choices first to facilitate faster execution. While the "default" is not required, it is recommended.

If you need to have several choices give the same response, you need to use the following coding style: switch (value) { case (1): case (2): case (3): { //The case code for 1, 2, 3 break; } case (4): case (5): case (6): { //The case code for 4, 5, 6 break; } default: { //The code for other values break; } }

Demo "if" Statement


/*This program calculates weekly pay for fast-food managers. The pay rate is $14.10 per hour. In addition, if total sales exceed $9400 a week, the manager receives a $100 bonus for that week.*/ #inlcude <iostream.h> #include <stdlib.h> #include <iomanip.h> #include "apstring.cpp" int main(void) { system("CLS"); apstring name; //declare apstring to hold name const int bonus = 100; //bonus is set constant double hours, total, pay; //Print and underline the headings cout<< "\n\nManager Pay Calculation Program\n"; cout<<"```````````````````````````````````````````````````\n\n"; //Get information from user at keyboard cout<<"Enter manager's full name: "; getline(cin,name); cout<<"How many hours did " <<name<<" work?"; cin>> hours; cout<<"What were the total weekly sales? "; cin>>total; pay = 14.1 * hours; //compute base pay

if (total > 9400) { pay += bonus; //bonus only if sales above 9400 //remember: pay = pay + bonus;

} cout.setf(ios::fixed); cout.setf(ios::showpoint); cout << "\n\n" <<name << " made $" <<setprecision(2) << pay <<"." <<endl<<endl<<endl; return 0; }

Demo successive "if" Statements


/*This program expresses my preferences of temperatures. Depending upon the conditions which need to be checked, a successive series of "if" statements may work nicely. BUT successive "if" statements can create a trap for you if you are not careful. See if you can see what is wrong with the logic used in the program below.*/ #inlcude <iostream.h> #include <stdlib.h> int main(void) { system("CLS"); int temp; cout<< "Please enter the temperature: "; cin>> temp; if (temp < 32) { cout<<"Brrrr!!! Where's the lodge?"; } if (temp >85) { cout<<"Sweat city!!! Where's the pool?";

} cout<< "Now, this temperature I like!!"; return 0; } /*The problem is that the last line ("Now, this temperature I like!!") is printed EVERY time - even when one of the "if" statements is true. This most likely was not the intent of this program. The "if ... else if ... if" structure would solve this problem more efficiently than adding yet another "if" statement to this program.*/

Demo "if ... else" Statements


//This program thinks EVERYONE loves C++. :-) #inlcude <iostream.h> #include <stdlib.h> int main(void) { system("CLS"); const int Yes = 1; const int No = 0; int response = No; //initialize the variable // to a zero //obtain user information cout<<"Do you like C++?" << endl; cout<<"(Enter 1 for YES or any other number for NO)"; cout<<endl; cin>>response; if (response = = Yes) { cout<<"Your choice is 'YES'."<<endl; cout<<"You had only one key for the right answer, "; cout<<"and you have pressed it."; }

else { cout<<"Your choice is 'NO'."<<endl; cout<<"Maybe you didn't understand the question."; cout<<"Re-run the program and try again, please."; } cout<<endl<<endl<<endl; return 0; }

Demo "if ... else if ... else" Statements


/*This program is used to reward employees for their years of faithful service to a teddy bear company.*/ #inlcude <iostream.h> #include <stdlib.h> int main(void) { system("CLS"); int years; cout<< "\n\nHow many years of" << " service? "; cin>> years; if (years > 20) { cout<<"\nYou get the gold watch teddy bear!!"; } else if (years > 10) //you already know years is not > 20 { cout<<"\nYou get a new paper weight teddy bear" <<" for your desk!!"; } else //you already know years is not >10 { cout<<"\nYou get a great big teddy bear"

<<" pat on the back!!"; } cout<<endl<<endl<<endl; return 0; }

Demo "switch" menu (with integer expression).


This is a Program Fragment ...
// Sample using numbers as menu choices. // Conversion program int choice; //Menu cout<<"1. LBS to OZS formula"<<endl; cout<<"2. Minutes to Seconds formula"<<endl; cout<<"3. Months to Weeks formula"<<endl; cout<<"Which formula would you like to see? "; cin>>choice; switch (choice) { case(1): { cout<<"Conversion to ounces:"<<endl; cout<<"16 ozs. = 1 pound"; break; } case(2): { cout<<"Conversion to seconds:"<<endl; cout<<"60 seconds = 1 minute"; break; } case(3): { cout<<"Conversion to weeks:"<<endl; cout<<"4 weeks = 1 month"; break; }

default: { cout<<"\a\a\a\a\aPlease enter only 1, 2 or 3!!"; cout<<endl; cout<<"Try again, please."; } }

Demo "switch" menu (with character expression).


This is a Program Fragment ...
//Sample using characters menu choices. char choice; //Menu cout<<"Available modes of transport:\n" cout<<"E - Enterprise"<<endl; cout<<"M - Millennium Falcon"<<endl; cout<<"T - Tie Fighter"<<endl; cout<<"Please make your choice from the menu: "; cin>>choice; switch (choice) { case('E'): { cout<<"The Enterprise departs on" <<" stardate 2067.3"<<endl; cout<<"Be prompt!"; break; } case('M'): { cout<<"The Falcon should depart at 1500 hours.\n"; cout<<"However, Han Solo is always late!"<<endl; break; } case('T'): { cout<<"The Tie Fighter has already departed.\n"; cout<<"You may want to use a transporter!";

break; } default: { cout<<"\a\a\a\a\aPlease enter only E, M or T!!"; cout<<endl; cout<<"Try again, please."; } }

Conditional Operator
You can exchange simple if-else code for a single operator the conditional operator. The conditional operator is the only C++ ternary operator (working on three values). Other operators you have seen are called binary operators (working on two values).

FORMAT:
conditional Expression ? expression1 : expression2;

** if the conditional Expression is true, expression1


executes, otherwise if the conditional Expression is false, expression 2 executes. If both the true and false expressions assign values to the same variable, you can improve the efficiency by assigning the variable one time: (a>b) ? (c=25) : (c=45); can be written as: c = (a>b) ? 25 : 45;

if (a>b) { c=25; } else { c=45; } can be replaced with (a>b) ? (c=25) : (c=45); The question mark helps the statement read as follows: "Is a greater than b? If so, put 25 in c. Otherwise, put 45 in c."

Increment and Decrement Operators


Adding or subtracting 1 from a variable is a very common programming practice. Adding 1 to a variable is called incrementing and subtracting 1 from a variable is called decrementing.

All are the same:


i = i + 1; i += 1; i++;

increment and decrement operators work only with integer variables -- not on floating point variables or literals. the C++ compiler is controlling the execution of the prefix and postfix operators. You cannot change this order of execution. For example, the parentheses below will not force an early execution: value = (((x--)))* num; //still decrements x last. one disadvantage of using the increment/decrement operators is that the variable can only be incremented or decremented by the value ONE. If you need to increment (or decrement) by a larger (or smaller) value, you must use statements like m += 2; or amount -= 5; be careful when combining increment and decrement operators inside expressions with logical operators. If in doubt, don't use them together. For example, do NOT use: if (( num1 = = 4 ) || ( num2 != ++j)) (j may not be incremented when (num1 = = 4) is TRUE.) Instead, separate the code to avoid this problem: ++j; if (( num1 = = 4) || (num2 != j))

++i; --i; increment or decrement occurs before the variable's value is used in the remainder of the expression.

Prefix:

Postfix:
i++; i--; increment or decrement occurs after the variable's value is used in the remainder of the expression.

The while loop


The while loop allows programs to repeat a statement or series of statements, over and over, as long as a certain test condition is true. The format is shown in the box to the right. The test condition must be enclosed in parentheses. The block of code is called the body of the loop and is enclosed in braces and indented for readability. (The braces are not required if the body is composed of only ONE statement.) Semi-colons follow the statements within the block only. When a program encounters a while loop, the test condition is evaluated first. If the condition is TRUE, the program executes the body of the loop. The program then returns to the test condition and reevaluates. If the condition is still TRUE, the body executes again. This cycle of testing and execution continues until the test condition evaluates to 0 or FALSE. If you want the loop to eventually terminate, something within the body of the loop must affect the test condition. Otherwise, a disastrous INFINITE LOOP is the result! ;-( The while loop is an entry-condition loop. If the test condition is FALSE to begin with, the program never executes the body of the loop. The following program fragment prints and counts the characters of a string array: apstring name="Corky"; i = 0; //begin with the first cell of array while (i< name.length( )) // loop test condition { cout<< name[ i ] << endl; //print each character i++; //increment counter by 1 } cout << "There are " << i << " characters.\n"; \*This last cout prints when the test condition is false and the loop terminates*\

FORMAT:
while(test condition) { block of code; }

iteration - doing the same thing again and again.

Ending a Program or Loop Early


On occasion, it may be necessary to end a program (or section of a program) earlier than its normal termination. Below are examples of methods of interrupting or terminating programs or loops.

return 0;
- it is possible to end a program (or function) prior to its normal termination by using an "extra" return 0; statement. The drawback to this strategy is that it ends the entire program (or function) at the point where the return 0; statement is placed. This may not always be what you had in mind. Oftentimes, the programmer may wish to simply end a "process" within the program, but continue with the remainder of the programming code. return 0; returns a value of 0 to the IDE indicating that the program reached normal termination.

exit( );
- the exit( ) function also ends a program before its normal termination. It requires the Standard Library header file, stdlib.h. The format is exit(value); where value is an integer variable or value. Using exit(1); returns a value of 1 to the IDE indicating that an error must have occurred. This process is often used for error trapping.

break;

- the break statement gets you out of a loop. No matter what the loop's ending condition, break immediately says "I'm outta here!" The program continues with the next statement immediately following the loop. Break stops only the loop in which it resides. It does not break out of a "nested loop" (a loop within a loop).

continue;
- continue performs a "jump" to the next test condition in a loop. The test condition is then evaluated as usual, and the loop is executed as long as the test condition remains true. The continue statement may be used ONLY in iteration statements (loops). It serves to bypass, or jump over, certain iteration sections of a loop.

The do-while loop


The do-while loop is similar to the while loop, except that the test condition occurs at the end of the loop. Having the test condition at the end, guarantees that the body of the loop always executes at least one time. The format of the do-while loop is shown in the box at the right. The test condition must be enclosed in parentheses and FOLLOWED BY A SEMI-COLON. Semi-colons also follow each of the statements within the block. The body of the loop (the block of code) is enclosed in braces and indented for readability. (The braces are not required if only ONE statement is used in the body of the loop.) The do-while loop is an exit-condition loop. This means that the body of the loop is always executed first. Then, the test condition is evaluated. If the test condition is TRUE, the program executes the body of the loop again. If the test condition is FALSE, the loop terminates and program execution continues with the statement following the while. do {

FORMAT:

} while (test condition);

block of code;

/*The following program fragment is an input routine that insists that the user type a correct response -in this case, a small case or capital case 'Y' or 'N'. The do-while loop guarantees that the body of the loop (the question) will always execute at least one time.*/
char ans; do { cout<< "Do you want to continue (Y/N)?\n"; cout<< "You must type a 'Y' or an 'N'.\n"; cin >> ans; } while((ans !='Y')&&(ans !='N')&&(ans !='y')&&(ans !='n'));

exit condition loop

/*the loop continues until the user enters the correct response*/

The for loop


The statements in the for loop repeat continuously for a specific number of times. The while and do-while loops repeat until a certain condition is met. The for loop repeats until a specific count is met. Use a for loop when the number of repetition is know, or can be supplied by the user. The coding format is: for(startExpression; testExpression; countExpression) { block of code; } The startExpression is evaluated before the loop begins. It is acceptable to declare and assign in the startExpression (such as int x = 1;). This startExpression is evaluated only once at the beginning of the loop. The testExpression will evaluate to TRUE (nonzero) or FALSE (zero). While TRUE, the body of the loop repeats. When the testExpression becomes FALSE, the looping stops and the program continues with the statement immediately following the for loop body in the program code. The countExpression executes after each trip through the loop. The count may increase/decrease by an increment of 1 or of some other value. Braces are not required if the body of the for loop consists of only ONE statement. Please indent the body of the loop for readability. CAREFUL: When a for loop terminates, the value stored in the computer's memory under the looping variable will be "beyond" the testExpression in the loop. It must be sufficiently large (or small) to cause a false condition. Consider: When this loop is for (x = 0; x <= 13; x++) finished, the value 14 is cout<<"Melody"; stored in x. The following program fragment prints the numbers 1 - 20.

for:
int ctr; for(ctr=1;ctr<=20; ctr++) { cout<< ctr <<"\n"; } Common Error: If you wish the body of a for loop to be executed, DO NOT put a semicolon after the for's parentheses. Doing so will cause the for statement to execute only the counting portion of the loop, creating the illusion of a timing loop. The body of the loop will never be executed.

Semicolons are required inside the parentheses of the for loop. The for loop is the only statement that requires such semicolon placement.

Which LOOP should I use????

while:

the loop must repeat until a certain "condition" is met. If the "condition" is FALSE at the beginning of the loop, the loop is never executed. The "condition" may be determined by the user at the keyboard. The "condition" may be a numeric or an alphanumeric entry. This is a good, solid looping process with applications to numerous situations.

The following program fragments print the numbers 1 - 20. Compare the different looping procedures. Remember, there are always MANY possible ways to prepare code!

do-while:
int ctr = 1; do { cout<< ctr++ <<"\n"; } while (ctr <= 20);

do-while:

operates under the same concept as the while loop except that the do-while will always execute the body of the loop at least one time. (Do-while is an exit-condition loop -- the condition is checked at the end of the loop.) This looping process is a good choice when you are asking a question, whose answer will determine if the loop is repeated.

for:
int ctr; for(ctr=1;ctr<=20; ctr++) { cout<< ctr <<"\n"; }

for:

the loop is repeated a "specific" number of times, determined by the program or the user. The loop "counts" the number of times the body will be executed. This loop is a good choice when the number of repetitions is known, or can be supplied by the user.

while:
int ctr = 1; while (ctr < = 20) { cout<< ctr++ <<"\n"; }

Nested Loops
We have seen the advantages of using various methods of iteration, or looping. Now let's take a look at what happens when we combine looping procedures. The placing of one loop inside the body of another loop is called nesting. When you "nest" two loops, the outer loop takes control of the number of complete repetitions of the inner loop. While all types of loops may be nested, the most commonly nested loops are for loops.

nested loops

Let's look at an example of nested loops at work.


We have all seen web page counters that resemble the one shown below ( well, OK, maybe not quite this spastic!!). Your car's odometer works in a similar manner.

This counter (if it worked properly) and your car's odometer are little more than seven or eight nested for loops, each going from 0 to 9. The far-right number iterates the fastest, visibly moving from 0 to 9 as you drive your car or increasing by one as people visit a web site. A for loop which imitates the movement of the far-right number is shown
below:

for(num1 = 0; num1 <= 9; num1++) { cout << num1 << endl; } The far-right number, however, is not the only number that is moving. All of the other numbers are moving also, but at a much slower pace. For every 10 numbers that move in the column on the right, the adjacent column is incremented by one. The two nested loops shown below may be used to imitate the movement of the two far-right numbers of a web counter or an odometer:

The number of digits in the web page counter or the odometer determine the number of nested loops needed to imitate the process.

When working with nested loops, the outer loop changes only after the inner loop is completely finished (or is interrupted.).
Let's take a look at a trace of two nested loops. In order to keep the trace manageable, the number of iterations have been shortened. for(num2 = 0; num2 <= 3; num2++) { for(num1 = 0; num1 <= 2; num1++) { cout<< num2<< " " << num1<< endl; } }

Memory
int num2 0 int num1 0 1 2 3 end loop 1 0 1

Screen
0 0 0 1 1 1 2 2 2 3 0 1 2 0 1 2 0 1 2 0

2 3 end loop 2 0 1 2 3 end loop 3 0 1 2 3 end loop 4 end loop Remember, in the memory, for loops will register a value one beyond (or the step beyond) the requested ending value in order to disengage the loop.

3 1 3 2

Demo While Loop Fragments


// To print a horizontal row of 50 asterisks:
(remember that there are many ways of accomplishing this task)

int number = 0; while (number < 50) { cout << "*"; number++; } cout<<"\n Here are "<<number <<" stars";

int number = 1; while (number <= 50) { cout << "*"; number++; } cout<<"\nHere are "<<number<< " stars";

// To print the numbers 4 - 14 on a single line:


int num = 4; while (num < 15) { cout << num++ << " "; } int num = 4; while (num <=14) { cout << num++ << " "; }

// Program quits when a -1 is entered:


(using a specified number to terminate a situation is called using a "sentinel" value) (Notice that the first cin statement is needed to "prime" the while loop.)

int count = 0; int grade; cout << "Please enter grade ( enter -1 to quit)"; cin >> grade; while (grade != -1) { count++; cout << "Grade # " << count << " is " << grade << endl; cout << "Please enter grade ( enter -1 to quit) "; cin >> grade; }

Demo Fragments Ending a Program or Loop Early


// using break within a loop // eliminating the letter c apstring puppy = "DipStick"; int count = -1; while (count < 8) { count++; if (puppy[count]=='c') break; cout << puppy[count] << "\n"; } cout<< "Isn't this puppy a cutie!!"; Screen display: D Screen display: D // using continue within a loop // eliminating the letter c apstring puppy="DipStick"; int count = -1; while (count < 8) { count++; if ( puppy[count] =='c') continue; cout << puppy[count] << "\n"; } cout<< "Isn't this puppy a cutie!!";

i p S t i Isn't this puppy a cutie!!

i p S t i k Isn't this puppy a cutie!!

// using exit ( ) if ((age < 19) && ( grade >= 85) && (infractions == 0)) exit(1); // program STOPS here. Nothing else will be printed. if (grade < 85) cout<< "Your grades need to improve.\n"; cout<<"You are not eligible this semester. Try again next semester."; // using return 0 apstring name; if (name != "Donald") return 0;

// program STOPS here. Nothing else will be printed.

cout << "You receive a discount of 15%. \n" << "Your cost is " << .85 * cost << "\n"; return 0; }

Do...While Demo Fragments


// To print the message HAPPY HOLIDAYS 10 times; const char BEEP = '\a' // remember that '\a' sounds the beep int counter = 0; do { cout<< "HAPPY HOLIDAYS! \n" << BEEP; counter++; } while (counter <10);

// To add a total, count, and average grades: double total = 0; // be sure to initialize variables to zero to avoid ... int counter = 0; // ... allowing the computer to use it's "garbage". double average = 0; int grade; // Why is this variable not set equal to zero? It is filled by user. do { cout<< "Enter the grade scored. \n"; cout<< "Enter -999 to quit. \n"; cin>> grade; if (grade != -999) { total += grade; counter++; } } while (grade != -999); average = total / counter; cout<< "\n\n The average of your " << counter << " grades is " << average << ".\n"; // separating sections of the program // by inserting an empty line helps organize // your thinking and allows for easy reading.

Sample Fragments using the for loop


// Counting from 10 to 50 in increments (steps) of 5: int x; for ( x=10; x <= 50; x = x+5 ) //**increment/decrement won't work here. { // x = x + 5 could also be written x += 5 cout<< "Loop counter value is " << x << ".\n"; }

//Counting from 50 to 10 backwards in increments of 5: int x;

for ( x=50; x >= 10; x = x-5 ) // x = x - 5 could also be written x -= 5 { cout<< "Loop counter value is " << x << ".\n"; }

// Declaring and assigning the startExpression within the for loop: //Counting down from 10 to Blast Off for ( int i = 10; i >= 1; i-- ) // notice the int within the parentheses { cout<< i << '\n'; } cout<< "Blast off!\n";

// Delcare loop body variables outside of the loop: apstring child; // if declared within the loop, these variables would be re-declared int age; // ...each time the loop repeated, possibly causing problems. for (int ctr = 1; ctr <= 35; ctr++) { cout << "Enter the child's name: "; cin >> child; cout << "Enter the child's age: "; cin >> age; if ((age >= 6) && (age <=7)) { cout <<"\n" <<child<< " has Mr. Escalente for a teacher.\n"; } else { cout<<"\n" <<child<< " does not have Mr. Escalente for a teacher.\n"; } // Quits after 35 children's names are entered.

// User determines the length of for loop: cout << "How many stars do you want printed? "; cin >> num; cout << "Here are your stars: \n";

for (int i = 1; i <= num; i++) { cout << * << " "; }

// Printing titles and for loops: // print titles OUTSIDE the loop to prevent multiple copies of the title //print even numbers from 1 to 20 with title cout << "Even numbers from 1 to 20: \n"; //title is outside loop for (int num = 2; num <= 20; num += 2) { cout << num << " " ; } //notice startExpression //prints the even numbers

Sample Fragments using nested for loops


Nested FOR loops are often used to produce DESIGNS:

// The Isosceles Right Triangle (made with capital letters) char outer, inner; for (outer = 'F' ; outer >= 'A' ; outer--) { for (inner = 'A' ; inner <= outer; inner++) { cout <<inner; } cout<< "\n"; }

ABCDEF ABCDE ABCD ABC AB A

// Rectangle comprised of x's for (rows = 0; rows < 4; rows++) {

xxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxx

for (col = 0; col < 12; col++) { cout << 'x' ; } cout<< "\n"; }

xxxxxxxxxxxx

// Isosceles triangle of x's centered on column 15 for(i =0; i<=3;i++) { gotoxy(15-i, 5+i); for(int j=1; j<=2*i+1; j++) cout<<"x"; //print the x's cout<<endl; }

x xxx xxxxx xxxxxxx

Multiple Choice C++ Quiz


Unit 4 - Looping
Directions: Choose the best answer. Use the button at the bottom to check your answers. 1. Each pass through a loop is called a/an [a] enumeration [b] iteration [c] culmination [d] pass through

2. Which looping process checks the test condition at the end of the loop? [a] for [b] while [c] do-while

[d] no looping process checks the test condition at the end

3. A continue statement causes execution to skip to [a] the return 0; statement [b] the first statement after the loop [c] the statement following the continue statement [d] the next iteration of the loop

4. In a group of nested loops, which loop is executed the most number of times? [a] the outermost loop [b] the innermost loop [c] all loops are executed the same number of times [d] cannot be determined without knowing the size of the loops

5. The statement i++; is equivalent to [a] i = i + i; [b] i = i + 1; [c] i = i - 1; [d] i --;

6. Which looping process is best used when the number of iterations is known? [a] for [b] while [c] do-while [d] all looping processes require that the iterations be known

7. What's wrong? for (int k = 2, k <=12, k++) [a] the increment should always be ++k [b] the variable must always be the letter i when using a for loop [c] there should be a semicolon at the end of the statement [d] the commas should be semicolons

8. What's wrong? while( (i < 10) && (i > 24)) [a] the logical operator && cannot be used in a test condition [b] the while loop is an exit-condition loop [c] the test condition is always false [d] the test condition is always true

9. If there is more than one statement in the block of a for loop, which of the following must be placed at the beginning and the ending of the loop block? [a] parentheses ( ) [b] braces { } [c] brackets [ ] [d] arrows < >

10. What's wrong? (x = 4 && y = 5) ? (a = 5) ; (b = 6); [a] the question mark should be an equal sign [b] the first semicolon should be a colon [c] there are too many variables in the statement [d] the conditional operator is only used with apstrings
1. B 2. C 3. D 4. B 5. B 6. A 7. D 8. C 9. B 10.B

Using Functions in C++

A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses: int main(void). Good C++ programmers write programs that consist of many of these small functions. These programmers know that a program written with numerous functions is easier to maintain, update and debug than one very long program. By programming in a modular (functional) fashion, several programmers can work independently on separate functions which can be assembled at a later date to create the entire project. Ideally, your main( ) function should be very short and should consist primarily of function calls. Each function has its own name. When that name is encountered in a program, the execution of the program branches to the body of that function. When the function is finished, execution returns to the area of the program code from which it was called, and the program continues on to the next line of code.

Functions come in two varieties:


Built-in functions
Build-in functions are part of the compiler package, such as exit(1);

User-defined functions
User-defined functions are created by you, the programmer.

Creating User-Defined Functions 1. Declare the function. The declaration, called the function prototype, tells the computer the name, return

type, and parameters of the function. This statement is placed after #include<iostream.h> (and other headers) and before int main(void).

FORMAT NOTE:
Please have all of your functions end with return.

*Note: In this first


course, we will be using the word argument and parameter interchangeably. There is, however, a subtle difference between these two terms. Simply stated, an argument is the value passed to the function and the parameter is the variable that received the value.

2. Define the function. The function definition tells the


compiler what task the function will be performing. A function definition cannot be called unless the function is declared. The function prototype and the function definition must agree EXACTLY on the return type, the name, and the parameters. The only difference between the function prototype and the function header is a semicolon (see diagram below). The function definition is placed AFTER the end of the int main(void) function. The function definition consists of the function header and its body. The header is EXACTLY like the function prototype, EXCEPT that it contains NO terminating semicolon.

Style 1: void functionName(void)


Our first style of function will simply perform an independent task. It will not send or receive any parameters and it will not return any values. The word void appears as the return type and the parameters. //Example program //Screen display shown at the right //Prototyping, defining and calling a function #include<iostream.h> #include<stdlib.h> void astericks(void); //function prototype int main(void) { system("CLS"); cout<<"Heads up, function!\n"; astericks( ); //function call cout<<"Again, function!\n"; astericks( ); //function call cout<<"Job well done!\n"; return 0; //main( ) is over - ALL STOP!! } //function definition void astericks(void) { int count; // declaring LOCAL variable for(count = 1; count<=10; count++) cout<<"*"; cout<<endl; return; //return value is VOID, no return

Local Variable
..a variable that is restricted to use within a function of a program.

SCREEN DISPLAY
Heads up, function! ********** Again, function! ********** Job well done!

*Note:

One of the important features of functions is their ability to be reused. Notice how the function astericks() was called twice from main(). The programmer did not have to duplicate the code.

Style 2: void functionName(argument(s))


Our second style of function will take arguments (parameters) but will not return a value. The argument list in the parentheses specifies the types and number of arguments that are passed to the function. void sum(int x, int y, int z); //function prototype Using variable names in the prototype does not actually create the variables. It merely states the "type" of variables that will be used. Within the program, the function call sends actual values to the function to be processed by the function. sum(75, 95, 83); //function call

STOP!!
invalid function header
void sum(int x, y, z) { ....

//Example program //Screen display shown at the right //Passing arguments to a function #include<iostream.h> #include<stdlib.h> void greeting(int x); //function prototype int main(void) { system("CLS"); greeting(5); //function call- argument 5 int number; do { cout<<"Please enter value(1-10):\n "; cin>>number; }

Acceptable Prototypes
void add(int x, int y); void add(int, int); While both of these prototypes are acceptable, we will be using the first style.

while ((number < 1) || (number > 10)); greeting(number); //argument is a variable return 0; } //function definition void greeting(int x) // formal argument is x { int i; // declaring LOCAL variable for(i = 0; i < x; i++) { cout<<"Hi "; } cout<<endl; return; //return value is VOID, no return }

Screen Display
Hi Hi Hi Hi Hi Please enter value(1-10): 4 Hi Hi Hi Hi

Style 3: non-void functionName(void)


Our third style of function takes no arguments, but will return a value. Up until now, we have been communicating information TO a called function. Now we will be returning information FROM the function by using the function return value. The return value can be a constant, a variable, or an expression. The only requirement is that the return value be of the type specified in the function prototype. return_type functionName(void) //function header { statements; return (value); //value is of type return_type }

Function calls that return values need to have a place in main for the returned value to reside, to be printed, or to be manipulated. Think of the function as holding out its
hand to pass a value back to main. Main must stretch out its hand

NOTE:
Functions can return only ONE

(which may be a variable location) for this value to reside. Always be sure to do something with a returned value! Store the return value somewhere; print the return value to the screen; use the return value in a calculation; just use it!! The following are examples of USES of function return values: (Function calls with return locations) x = Avg( i, j) (Function Avg takes i and j and returns a value stored in x.) cout<< num(1,3,5); (Function num takes 1, 3 and 5 and its return value is
printed)

value.

Equivalent: return 0; return (0);

ans=add(a,b) + add(c,d); (Function add is called twice. The return


values from 2 calls are added and stored in ans.)

//Example program //Screen display shown at the right //Returning values from a function #include<iostream.h> #include<stdlib.h> void greeting(int x); //prototype-no return int getNumber(void); //prototype-return integer int main(void) { system("CLS"); greeting(5); //function call int response; response=getNumber( ); //call and store value greeting(response); //function call return 0; } //function definition - creates a line of "Hi"s void greeting(int x) { int i;

Screen Display
Hi Hi Hi Hi Hi Please enter number (1-10) 3 Hi Hi Hi

for(i = 0; i < x; i++) { cout<<"Hi "; } cout<<endl; return;

//function definition - get the user's # and return it int getNumber(void) { int number; do { cout<<"Please enter number (1-10)\n"; cin>>number; } while((number < 1)||(number > 10)); return (number); }

Style 4: non-void functionName(arguments)


Our fourth style of function takes arguments AND returns a value. //Example program with driver and function //Screen display shown at the bottom //A minimum value function #include<iostream.h> #include<stdlib.h> int min(int x, int y); //function prototype int main(void) // driver program { system("CLS"); int test1 = 12, test2 = 10; //arbitrary test values cout<<"The minimum of "<< test1 << " and " << test2 << " is " << min(test1, test2) << ".\n"; return 0; } //function definition int min(int x, int y) { int minimum; if (x < y) minimum = x; else minimum = y; return (minimum); }

NOTE:
A short program designed to test a function is called a driver.

Alternative Function Code


(uses conditional operator)

int min(int x, int y) { return((x<y)? x : y); }

Alternative codings for this function appear at the right. Remember, there are always many ways to accomplish a task.

(uses multiple returns)

Alternative Function Code

int min(int x, int y) { if (x < y) return x; else return y; }

Screen Display: The minimum of 12 and 10 is 10.

Demo Programs for Style 1 void functionName(void)


// Example program 1 // Defining, prototyping, and calling a function. #include <iostream.h> #include <stdlib.h> void country(void); // function declaration - function prototype int main(void) { system("CLS"); cout<< "I'm Joe Main, and I am calling a function named Country Sue!"; country( ); return 0; } // function definition void country(void) { cout<< "Hi, Joe. Country Sue here!\n"; return; } /* since the return value is void, NO number is specified with this return. */ // function call

Screen: I'm Joe Main, and I am calling a function named Country Sue! Hi, Joe. Country Sue here!

//Example program 2 with LOCAL variable

// letterhead for a animal shelter #include <iostream.h> #include <stdlib.h> void starline(void); int main(void) { system("CLS"); starbar( ); // function call // prototype the function

cout<< "\t\t All Creatures Big and Small Shelter\n"; cout<< "\t\t Lacona, New York \n"; cout<< "\t\t USA \n"; starline( ); return 0; } // function definition void starline(void) { int count; // declaring a LOCAL variable for(count = 1; count <=65; count++) cout<< "*"; cout<<endl; return; } Screen: ***************************************************************** All Creatures Big and Small Shelter Lacona, New York USA ***************************************************************** // function call

Demo Program for Style 4 non-void functionName(argument(s))


// Example program #include <iostream.h> #include <stdlib.h> double timesTwo(double num); // function prototype int main(void) { system("CLS"); double number, response; cout<<"Please enter a number:"; cin>>number; response = timesTwo(number); //function call cout<< "The answer is "<<response; return 0; } //timesTwo function doubel timesTwo (double num) { double answer; //local variable answer = 2 * num; return (answer); } Notice how the variable in the function (num) does not have the same name as the variable sent to the function (number). It makes no difference what the variables are called, as long as they are of the same variable type. Variables are used in the order in which they are sent to the function.

Review Tracing Program Fragments What screen output is produced by each of the following program fragments?

1.

cout<< cout<< cout<< cout<<

"W" << endl; endl << "\n"; endl << "O" << endl; "W" << endl;

2.

for(int i = 2; i <=5; i++) cout<< "*"; cout<< i;

3.

apstring hero = "Indiana"; int count = -1; while (count < 6) { count++; if (hero[count] =='d') continue; cout<< hero[count]; }

4.

int growl = 5; int meow = growl++ * 3;

cout<< growl << " " << meow << endl;

5.

int age = 30; if (age <15) cout<< "Skeeter"; else if (age>20) cout<< "Duke"; else cout<< "Wally";

6.

cout<< (10 - -8)/6 * 3 << endl; cout<< 5 + -2*3 + 8/2 << endl; cout<< 7/2 + 7%2;

7.

int x = 3; int y = 6; if(x>=3) cout<< "Zip Drive"<< endl; if((x<=3) && (y>6)) cout<< "Scanner" << endl; if((x<=3)||(y>6))

cout<< "CD Burner";

8.

int a = 1, b = 2; while (b < 8) { b += a; a += 3; } cout<< a << " " << b;

9.

int i, j, sp; for (i = 0; i <= 3; i++) { for(sp=0; sp<=15-i; sp++) cout<< " "; for(j=1; j<=2*i+1; j++) cout<< "&"; cout<< endl; }

10. cout<<setprecision(2)<<3.567;

11.

x = 2; switch(x) { case (1): cout<< "A"; case (2): cout<< "B"; case (3): cout<< "C"; }

12.

if (!3) { cout<< "Trick"; } cout<< "Yes";

13. #include <iostream.h> void goodies(void); void moreGoodies(int x, int y); int grandGoodies(void); int main(void) { goodies( ); int a = 2, b = 3; moreGoodies(a, b); cout<< a << " " << b << endl; cout<< grandGoodies( ); return 0; }

//**function definition void goodies(void) { cout<< "Goodies! \n"; return; } //**function definition int grandGoodies(void) { return (100); } //**function definition void moreGoodies(int x, int y) { y = ++y - 1; x = x-- * 2; cout<< x << " " << y << endl; return; }

14.

What is WRONG with this segment of code? for ( int x = 6; x > 6; x--) { cout<< x; }

15.

What is WRONG with this segment of code? int num = 7; do { cout<< "LookOut!"; num -= 2; } while (num != 2);

16.

What's wrong with this fragment of code? int pop = 8; do { cout<< "Howdy, partner!"; pop *= 2; } while (pop%2 == 0);