Sie sind auf Seite 1von 418

The C++ Programming Language

History of Programming Languages Flowcharting Introduction to C++ Programming Fundamental Data Types O Operators for f Fundamental F d l Data D Types T The C++ Mathematical Functions Making Decisions Iteration Statements Formatting and Manipulators Arrays Pointers Functions User-Defined Data Types Classes

History of Programming Languages

What Is a Programming Language? History of C and C++ FORTRAN and COBOL Pascal and Basic Windows Programming The .NET platform

What Is a Programming Language?


Programming P i is i the th ability bilit to t t talk lk t to th the computer t in i a language it can understand and using grammar and syntax th t it can follow that f ll to t get t it to t perform f useful f l tasks t k for f you. You write code and the computer interprets your request and does something. The first computers were not too different than a light switch. These early computers consisted of wires and switches in which the electrical current followed a path dependent on which switches were in the on or off position. Each switchs position could be expressed as a number: 1 for the on position, 0 for the off position. Thus, the instructions given to these first computers, in the form of the switches positions, essentially were a series of ones and zeroes.

The first computers cost millions of dollars. Programmers were forced to program in a language in which all the instructions were reduced to a series of numbers, called machine language. This language could be directly input into the computer. A typical machine-language machine language program looks like: 1010 1111 0011 0111 0111 0110 .. and d so on f for several l h hundred d d i instructions t ti

While machines think in ones and zeroes, people don't. To program these ancient machines, machines software engineers would write their programs using a simple language in which each word in the language stood for a single instruction. This language was called assembly language because the programmers had to hand translate, or assemble, each line into machine code. A typical program might look like: Program MOV A,47 ADD A, B HALT Translation 1010 1111 0011 0111 0111 0110

.. and so on for several hundred instructions Thi process i This is ill illustrated t t d in i the th following f ll i figure. fi

Assembling a program

Translation was a difficult, tedious, and exacting task. One software engineer decided that this was a perfect job for a computer, so he wrote a program called an assembler that would do the job automatically.

Todays computers, of course, are far more powerful than y computers. p However, , the language g g that computers p these early understand, the machine language, remains the same. A complex program may consist of thousands or even millions of step-by-step machine language instructions, which would require an inordinately long amount of time to write. Over the years, a series of higher-level languages have been devised. These languages attempt to let the programmer write it i in a medium di th that t is i easy for f him hi to t understand. d t d Programming languages are far more understandable to programmers than machine language or assembly assembl language because programming languages resemble the structure and syntax of human language. language Additionally, Additionally code can be written much faster with programming languages than assembly g g because one p programming g g language g g instruction language can cover many machine language instructions.

C++ is one of many programming languages. Other popular programming languages include Java Java, C# C#, and Visual Basic Basic. There are many others. Indeed, new languages are being created all the time. However, all programming languages have essentially the same purpose, which is to enable a programmer g to g give instructions to a computer. p human p Why learn C++ instead of another programming language? C++ is i the th most t widely id l used d programming i language l and di is an industry standard for programming applications of all kinds C++ is often the best language to use when writing kinds. games. In addition, C++ is a highly efficient programming language that can conserve resources more effectively than languages such as Visual Basic or Delphi.

History of C and C++


C++ evolved l d from f C which C, hi h evolved l d f from a previous i programming language, called B. In 1972 Dennis Ritchie created a language based on BB language which he eventually called C. C brought with it simplicity, efficiency, and flexibility and heralded a new age in programming in which it was possible to do a lot more with less code, more quickly and easily than before. C became the development language of the UNIX operating system. Today, most operating systems are written in C and/or C++. In 1980 the C++ programming language was created by Bjarne Stroustrup and his team at Bell Laboratories to help i l implement simulation i l i projects j i in an object-oriented bj i d and d efficient way. C++ was derived from the C programming language: ++ is the increment operator in C. C

FORTRAN and COBOL


Hundreds of high-level languages have been developed, but only a few have achieved broad acceptance. FORTRAN (FOR l TRANslator) (FORmula TRAN l t ) was d developed l d by b IBM Corporation C ti in the mid-1950s to be used for scientific and engineering applications that require complex mathematical computations. FORTRAN is still widely used, especially in engineering applications. COBOL (COmmon Business Oriented Language) was developed in the late 1950s by computer manufacturers, manufacturers the U.S. government and industrial computer users. COBOL is used for commercial applications that require precise and efficient manipulation of large amounts of data. Much programmed g in COBOL. business software is still p

Pascal and Basic


The Pascal Th P l programming i language l was developed d l d b by Professor Niklaus Wirth in 1971. Named after the seventeenth-century mathematician and philosopher Blaise Pascal, it was designed for teaching structured programming p y became the p preferred p programming g g language g g in and rapidly most colleges. Pascal lacks many features needed in commercial, industrial and government applications, so it has not been widely accepted in these environments. The BASIC (Beginner's All-purpose Symbolic Instruction Code) programming language was developed in the mid-1970s at Dartmouth College as a means of writing simple programs. BASIC' primary BASIC's i purpose was to familiarize f ili i novices i with ih programming techniques.

Windows Programming
When Microsoft designed Windows, the company decided to provide a library of functions so that people could design Windows programs. This library is called the Windows API (Application Programming Interface). A subset of this library is called the Windows GUI (Graphic User Interface). Using the Windows GUI, you can make your programs more interesting by adding command buttons, scrolling lists, icons, and other Windows elements that users can employ to interact with your programs.

Using C and the native APIs is not the only way to write programs for f Windows. Wi d However, H this thi approach h offers ff you th the best performance, the most power, and the greatest versatility in exploiting the features of Windows Windows. Executables are relatively small and don't require external libraries to run. Most importantly, importantly becoming familiar with the API provides you with a deeper understanding of Windows internals, regardless of how you eventually write applications for Windows. Microsoft Visual C++ with the Microsoft Foundation Classes Library (MFC) has been a popular alternative in recent years. years MFC encapsulates many of the aspects of Windows programming in a collection of C++ classes.

Microsoft's Visual Basic language, introduced in the early 1990s to simplify the development of Microsoft Windows applications, has become one of the most popular programming languages in the world. world Many programmers enjoy the ease of development environments such as Microsoft Visual Basic or Borland Delphi (which incorporates an object-oriented dialect of Pascal) These environments allow a programmer to focus Pascal). on the user interface of an application and associate code with user interface objects.

The .NET platform


Microsoft's Mi ft' latest l t t development d l t tools t l are part t of f its it corporatet wide strategy for integrating the Internet and the Web into computer applications. applications This strategy is implemented in Microsoft's .NET platform, which provides developers with the capabilities they need to create and run computer applications that can execute on computers distributed across the Internet. Microsoft's Microsoft s three primary programming languages are Visual Basic .NET (based on the original BASIC), Visual C++ .NET (based on C++) ( ) and C# ( (a new language g g based on C++ and Java that was developed expressly for the .NET platform). Developers using .NET can write software components in the language they are most familiar with and then form applications by combining those components with components written in any .NET language.

Flowcharting

Flowcharting
A program, like lik a river, i fl flows f from b beginning i i t to end. d Programmers may find it helpful, both in writing code and in understanding someone elses code, code to visually depict the flow of the program. Programmers use a flowchart P fl h tt to visually i ll depict d i t th the flow fl of fa program. Flowcharts use symbols. These flowcharting symbols represent different aspects of a program program, such as the start or end of a program, user input, how it displays on a monitor, and so on. on These symbols are joined by arrows which show the connections between different parts of the program and the direction of the program flow.

The commonly used flowchart symbols are: Beginning and end of a program Input and output Assignment and computation Desission C Connector t

ax 2 + bx + c = 0

:
. : x 5 + 3 x 2 10 = 0 . : x = 5 10 3 x 2 x x x . x ) (.

x .

:
: x x

: x1 x : n : i

:
(... : ) ( ) (. 2 . . (1+2+3++t )1+2+3+ +t ) (t ) (t-1 ) (t-2 ) t ( .

:
-

:
: )(value )(current value : : ) ( )(time )(method : : )(year : )(factor )(depreciation : : )(sum : : 1+2+3++t = t*(t+1)/2

v c t m y f d s

Introduction to C++ Programming

Developing a C++ Program Building a C++ Project Our First C++ Program Whitespace The Manipulator endl The Newline Character (\n) Using Comments

Developing a C++ Program

The following three steps are required to create and translate a C++ program:
1.

First, a text editor is used to save the C++ program in a t t fil text file. The Th code d a programmer writes it is i referred f d to t as source code, which is saved in a file that usually has a .cpp cpp extension, extension standing for C Plus Plus. Plus The source file is put through a compiler for translation. If everything works as planned, planned an object file made up of machine code is created. The object file is also referred to as a module. Finally, the linker combines the object file with other modules to form an executable file (.exe). These further modules contain functions from standard libraries or parts of the p p program g that have been compiled p p previously. y

2.

3.

Prior to compilation, header files, which are also referred to as include i l d files, fil can be b copied i d to t the th source file. fil Header H d fil files are text files containing information needed by various source files, files for example, example type definitions or declarations of variables and functions. Header files can have the file extension .h, h but they may not have any file extension. extension

Building a C++ Project


Visual C++ 6.0 60
1. 2. 3. 4.

Start the compiler. Choose File New from the menus. Choose Win32 Console Application and enter a project name, such as HELLO, and click OK. Choose An Empty Project from the menu of choices and click li k Finish. A dialog di l box b i is displayed di l d with i h new project j information. Cli k OK. You Click Y are t taken k b back k to t the th main i editor dit window. i d Choose File New from the menus. Choose C++ Source File and give it a name, such as hello. You enter this name into the File Name text box. Click OK. You are taken back to the main editor window.

5. 6. 7. 8.

9. 10. 11. 12. 13.

Write the code. Ch Choose B ild Build Build B ild h hello.exe ll f from the th menus. Check that you have no build errors. You can find this i f information ti near the th bottom b tt of f the th editor. dit Run the program by pressing Ctrl+F5 or by selecting Build Execute E t hello h ll from f the th menus. Press any key to end the program.

Visual C++ 2003 and above


1 1. 2. 3.

Start the compiler. compiler Choose File New Project from the menus. Choose Win32 Ch i Console Application i i and d enter t a project j t name, such as HELLO into the Name text box, and click OK. Click the Application Settings tab in the Application Wizard (or click next). ) Choose Empty Project from the menu of Additional Options and click Finish. You are taken back to the main editor window. Choose Project Add New Item from the menus. menus Choose C++ Source File and give it a name, such as hello. You enter this name into the Name text box. Click OK. You are taken back to the main editor window.

4. 5.

6 6. 7. 8.

9. 10. 11. 12. 13.

Write the code. Ch Choose B ild Build Build B ild h hello ll from f the th menus. Check that you have no build errors. You can find this i f information ti near the th bottom b tt of f the th editor. dit Run the program by pressing Ctrl+F5 or by selecting D b Debug Start St t Without With t Debugging D b i f from the th menus. Press any key to end the program.

Our First C++ Program


#include #i l d <iostream.h> <i t h> int main() { cout << "Welcome to C++!"; return 0; }

Output
Welcome to C++!

Note:
If you use Visual C++ 2003 and above, you should always write #include <iostream> using namespace std; instead of #include <iostream.h>

Analysis
On the O th first fi t line, li the th file fil iostream.h i t h is i i included l d d into i t the th current file. Heres how that works: The first character is the # symbol which is a signal to a program called the preprocessor. symbol, preprocessor Each time you start your compiler, the preprocessor is run first. The p preprocessor p reads through g y your source code, , looking for lines that begin with the pound symbol (#) and acts on those lines before the compiler runs. The command #include is a preprocessor instruction that says, What follows is a filename. Find that file, read it, and place it right here. The angle brackets around the filename tell the preprocessor to look in all the usual places for this file. file The file iostream.h iostream h (input-output-stream) (input output stream) is used by cout, which assists with writing to the console. The effect of this line is to include the file iostream.h iostream h into this program as if you had typed it in yourself.

The actual program starts with the function named main(). y C++ p program g requires q a function called main(), (), not Every Main() or MAIN() or mane(). When you run a C++ program, execution always begins at the beginning of the main() function. Therefore, if you dont have main(), you dont have a complete program, and the compiler points out th t you havent that h t defined d fi d a main() i () function. f ti A function is a block of code that performs one or more actions. ti main() i (), like lik all ll f functions, ti must t state t t what h t kind ki d of f value it returns. The return value type for main() in our program is int, which means that this function returns an integer to the operating system when it completes. The main() function ends with the closing brace (}). ) All functions begin with an opening brace ({) and end with a g brace (}). Everything y g between the opening p g and closing closing braces is considered a part of the function.

There are two statements in the program: cout << "Welcome Welcome to C++!"; C++! ; return 0; The first statement tells the computer p to display p y the q quoted phrase. Most statements tell the computer to do something. j cout (pronounced p C out) is used to p print a The object string to the screen. This object is used in C++ to handle output to the console. Heres how cout is used: Type the word cout, followed by the insertion operator (<<). The insertion operator directs the string on its right to cout, which sends it to the display. displ Wh te er follows Whatever follo s the insertion i sertio operator oper tor is written to the console. If you want a string of characters written be certain to enclose them in double quotes ("). written, ) A semicolon signals the end of the statement. This is a crucial part of the syntax p y but easy y to forget. g If y you leave out the semicolon, the compiler will signal an error.

The last statement in the function body is return 0;. This t ll main() to tells t return t the th value l 0 to t whoever h called ll d it it, in i this thi case the operating system. A value may be returned to the operating system to indicate success or failure, failure or using a failure code to describe a cause of failure. The previos C++ example have the following elements:

A preprocessor #include directive A function heading: int main() A function body, delimited by { and } A statement that uses cout to display a message A return statement to terminate the main() function

Whitespace
Whitespace (t Whit (tabs, b spaces, and d newlines) li ) is i generally ll i ignored d in statements. The assignment x = a + b; could be written as x=a+b; or as x + =a b ;

Although this last variation is perfectly legal, it is also perfectly foolish. Whitespace should be used to make your programs more readable and easier to maintain.

Modifying Our First C++ Program


#include <iostream.h> int main() { cout << "Welcome "; cout << "to C++!"; return 0; }

Output
Welcome to C++!

Note that the cout facility does not move automatically to the next line when it prints a string string, so the first cout statement leaves the cursor positioned just after the space at the end of the output string. The output for each cout statement begins where the last output ended.

The Manipulator endl


endl is a special C++ notation that represents the important concept of beginning a new line. Inserting endl into the output stream causes the screen cursor to move to the beginning of the next line.

Example: cout << cout << cout << or: cout << cout << Output:

"Enjoy yourself with C++!"; endl; "C++ is very efficient!"; "Enjoy yourself with C++!" << endl; "C++ is very efficient!";

Enjoy j y y yourself with C++! C++ is very efficient!

The Newline Character (\n)


C++ has another, another more ancient, ancient way to indicate a new line in output, the C notation \n, so you can write cout << "C++ is very y efficient!\n"; \ ; The \n combination is considered to be a single character called the newline character. It tells cout to put a new line after the words C++ is very efficient!. The newline character \n does the same job like endl. cout << "C++ is i very efficient!" ffi i ! << endl; dl If you are displaying a string, \n needs less typing. But if you want to generate a newline by itself itself, both approaches take the same amount of typing, but most people find endl to be more comfortable. cout << "\n"; //start a new line cout << endl; //start a new line Th newline The li character h t i is one example l of f special i l k keystroke t k combinations termed escape sequences.

Printing Multiple Lines of Text with a Single Statement


#include <iostream.h> int main() { cout << "Welcome\nto\n\nC++!\n"; return 0; }

Output
Welcome to C++!

Using Comments
When you are writing Wh iti a program, your i intent t ti is always l clear l to you. Funny thing thing, though a month later later, when you return to the program, it can be quite confusing and unclear. To avoid the confusing, and to help others understand your code, you need to use comments. Comments are text that is ignored by the compiler, but that can inform the reader of what you are doing at any particular point in your program. C++ comments come in two ways: single-line comments and multiline comments. Single-line comments are accomplished using a double slash (//). The double slash tells the compiler to ignore everything that follows, until the end of the line.

Multiline comments are started by using a forward slash followed by an asterisk (/*). ) This slash slash-star star comment mark tells the compiler to ignore everything that follows until it finds a star-slash star-slash (*/ /) comment mark. mark These marks can be on the same line or they can have one or more lines between them; however, every (/ /*) must be matched with a closing (*/). Many C++ programmers use the double double-slash slash, single single-line line comments most of the time and reserve multiline comments for blocking out large blocks of a program.

Sample program
#include <iostream.h> <iostream h> int main() { /* this is a comment and it extends until the closing star-slash star slash comment mark */ / cout << "Enjoy yourself with C++!\n"; // this comment ends at the end of the line cout t << "C++ i is very efficient!\n"; ffi i t!\ " // double-slash comments can be alone on a line /* as can slash-star comments */ return 0; }

Output
Enjoy yourself with C++! C++ is very efficient!

Fundamental Data Types


Using Variables The Basic Data Types Declaration of Variables Creating More Than One Variable at a Time Case Sensitivity The Assignment Operator l-value and r-value Characters Special Printing Characters The Boolean Type Input with cin Casting Constants Defining Constants with #define The Advantage of Constants

Using Variables
Programs need a way to store the data they use or create so that it can be used later in the programs execution. Variables and d constants t t offer ff various i ways to t represent, t store, t and d manipulate that data. In C++, I C++ a variable v ri bl is a pl place ce to store i information form tio . A variable v ri bl is a location in your computers memory in which you can store a value and from which you can later retrieve that value. Notice that variables are used for temporary storage. When you exit a program or turn the computer off, the information in variables is lost. Permanent storage is a different matter.

When you define a variable in C++, you must tell the compiler what type of variable it is: an integer integer, a floating floatingpoint number, a character, and so forth. This information tells the compiler how much room to set aside and what kind of value you want to store in your variable. It also allows the compiler to warn you or produce an error message if you accidentally attempt to store a value of the wrong type in your variable. All variables must be declared prior to their use. This is necessary because the compiler must know what type of data a variable i bl contains t i b before f it can properly l compile il any statement that uses the variable. You can place variable declarations anywhere in a program. program However, However its it s probably more readable if commonly used variables are located at the g g of the p program. g beginning

The Basic Data Types

T Type
short int int unsigned int long int unsigned long int float double char wchar_t bool

Si Size
2 bytes 4 bytes 4 bytes 4 bytes 4 bytes 4 bytes 8 bytes 1 byte 2 bytes 1 byte

Mi i Minimum V l Value M i Maximum V Value l


32,768 0 2,147,483,648 0 2,147,483,648 0 1.2 x 1038 2.2 x 10308 0 0 false (0) 32,767 65,535 2,147,483,647 4,294,967,295 2,147,483,647 4,294,967,295 3.4 x 1038 1.8 x 10308 255 65,535 true (1)

unsigned short int 2 bytes

Declaration of Variables
You create Y t or define d fi a variable i bl by b stating t ti it its type, t f followed ll d by b one or more spaces, followed by the variable name and a semicolon. The variable name can be any combination of letters, letters but it cannot contain spaces. Legal variable names include x, q , and myAge y g . Some declarations are shown here, , for J23qrsnf example: int x; char c; float balance; As a general programming practice, try to use expressive names such as myAge or howMany. Using good names makes it easier to understand the flow of your program. program Good variable names tell you what the variables are for, and they are easier to understand later when you are trying to figure out what you meant when you wrote that line of code.

Creating More Than One Variable at a Time


You can create more than h one variable i bl of f the h same type i in one statement by writing the type and then the variable names separated by commas names, commas. For example:
unsigned int age, weight; d bl area, width, double idth l length; th

As you can see, both age and weight are declared as unsigned integer variables. The second line declares three individual integer variables named area, width, and length. The type double is assigned to all the variables. Note that you can't mix types in one definition statement.

Case Sensitivity
C++ is C i case sensitive. iti In I other th words, d uppercase and dl lowercase letters are considered to be different. A variable named age is diff different tf from Age A , which hi h i is diff different tf from AGE. Incorrect I t case prevents the code from compiling successfully.

The Assignment Operator


You assign Y i a value l t to a variable i bl b by using i th the assignment i t operator (=). The assignment operator causes the operand on the left side of the assignment operator to have its value changed to the value on the right side of the assignment operator The expression operator.
int x; x = 38;

assigns the integer 38 to the variable x. You can combine Y bi th the steps t of f creating ti a variable i bl and d assigning i i a value to it. For example:
int width = 5;

Just as you can define more than one variable at a time, you can initialize more than one variable at creation. creation For example:
int i t width idth = 5, 5 length l th = 7; 7 short int myAge = 39, yourAge, hisAge = 40;

One unusual O l f feature t of f C++ i is th that t you can use th the assignment operator serially. The following is valid code:
int x, y, z; x = y = z = 88;

The assignment Th i t works k f from right i ht t to left. l ft First, Fi t 88 is i assigned i d to z; then the value of z, which is now 88, is assigned to y; then the value of y is assigned to x.

l-value and r-value


An l-value A l l i an operand is d th that t can be b on the th left l ft side id of f an expression. An r-value is an operand that can be on the right side of an expression. expression Note that all l l-values values are r-values, but not all r-values are l-values. An example of an r-value that is not an l-value is a literal. literal Thus, you can write x = 35; // ok But you cannot write 35 = x; // error, a literal is not an l-value!

Characters
Another type of variable you can have is a character variable. variable A character variable can hold a single just one character A character is anything that can be typed, character. typed such as the letters of the alphabet, the digits, and the other symbols you see on the computer keyboard. To use a character variable, you use the type name char. To initialize a character variable variable, you put your character inside single quotes. (If you use double quotes, the compiler issues an error message.) The following is an example of a character:
char answer; answer = 'y'; cout << "The character is: " << answer;

Character variables are typically 1 byte, enough to hold 256 p as a small number ( (0 to 255 values. A char can be interpreted for most compilers) or as a member of the ASCII set. In the ASCII code, all the lower- and uppercase letters, all the numerals, and all the punctuation marks are assigned a value between 1 and 128. For example the lowercase letter a is assigned i d the th value l 97 Another 97. A th 128 marks k and d symbols b l are reserved for use by the computer maker. When you put Wh t a character, h t for f example, l 'a', into i t a char variable, all that is really there is a number between 0 and 255. The compiler knows knows, however however, how to translate back and forth between characters and one of the ASCII values. It is important to realize, realize however, however that there is a big difference between the value 5 and the character '5'. The y valued at 53, , much as the letter 'a' is valued latter is actually at 97.

Special Printing Characters


The C++ compiler Th il recognizes i some special i l characters h t for f formatting. You put these into your code by typing the backslash (called the escape character), character) followed by the character. Thus, to put a tab character into your code, you g q quotation mark, , the backslash, , the letter would enter a single t, and then a closing single quotation mark:
cout << '\n' \n << '\t' \t << "Return Return and Tab\n"; Tab\n ;

This example uses two special printing characters, a carriage-return/linefeed ('\n' \n ) and a tab character ('\t' \t ), ) to print a message indented from the left on the screen. Note You can use double quotation mark with the special printing characters:
cout << "\n" << "\t" << "Return and Tab\n";

Escape Sequences
E Escape Description sequence
\ \n \r \b \t \v \a \\ \' \" N li (carriage Newline i return t and d linefeed li f d). )
of the current line; do not advance to the next line. line

Carriage return. Position the cursor to the beginning Backspace.

H i Horizontal t l tab. t b Vertical tab. Alert. Sound the system bell. Backslash. Used to print a backslash character. Single quote. Used to print a single quote character. Double quote. Used to print a double quote character.

The Boolean Type


The boolean type is the simplest data type. It is one byte long. It can store two values, true and false. Use the boolean type when h you h have only l t two possibilities. ibiliti F For example, l you might i ht have a variable named end, which is false until the program ends. d You Y can use thi this variable i bl t to fi find d out t whether h th youve reached the end of your program. You declare a boolean variable i bl using i th the keyword k d bool b l:
bool myBool; b l end; bool d myBool = true; ; end = false;

Input with cin


In your programming, I i you need d to set up the h capability bili f for users to use and store their input. You need a way to retrieve and d use i information f ti from f the th user when h the th program is i running (run-time), rather than when you are writing the program (design-time) (d i ti ) b because you cant t anticipate ti i t what h t users will write. You can store variables using the object cin (pronounced C in) much as youve stored them before, except now you d l declare the h name and d assign i its i value l l later. Th The cin object bj represents the keyboard or some other input device, whereas th cout object the bj t represents t th the screen or some other th output t t device.

Here is an example of storing a user-input data:


double radius; cout << "Radius = "; cin >> radius;

The statement
cin >> radius;

causes the program to wait for the user to type in a number. The resulting number is placed in the variable radius. The >> is the extraction or get from operator. It takes the value from the object cin and places it in the variable on its right. Notice that you use cin in much the same way that you use cout. Notice that the less-than signs are now greaterthan signs. These signs indicate that the computer is accepting data rather than printing it.

Naming Conventions
Various conventions exist for how to name variables, and although it doesnt much matter which method you adopt, it is important to be consistent throughout your program. Inconsistent naming will confuse other programmers when they read your code. Many programmers prefer to use all lowercase letters for their variable names. If the name requires two words (for example, my car), two popular conventions are used:
my_car or myCar.

Example 1:
int main() { int x = 10; int y = 11; int z = x * y; return 0; }

Example 2:
int main() { int width = 10; int length = 11; int area = width * length; return 0; }

Constants
Like variables, variables constants are data storage locations. locations Unlike variables, constants dont change. You must initialize a constant when you create it, and you cannot assign a new value later. The const keyword is used to create a "read only" object.

Example:
const double pi = 3.14159265;

The value of pi cannot be modified by the program. The following statement will result in an error message:
pi = pi + 2.0; //error //

Constant variables must be initialized with a constant expression i when h th they are declared d l d and d cannot t be b modified difi d thereafter: const int x; //error: x must be initialized x = 7; //error: cannot modify a const variable

Defining Constants with #define


Because a number of existing programs use the preprocessor #define directive, it is important for you to understand how it has been used used. To define a constant in this obsolete manner, manner you would enter this: #d fi #define studentsPerClass t d t P Cl 15 Note that studentsPerClass is of no particular type (int, char, and so on). The preprocessor does a simple text substitution. In this case, every time the preprocessor sees the word d studentsPerClass, it i puts i in the h text 15. Because the preprocessor runs before the compiler, your compiler never sees your constant; it sees the number 15. You should note that neither an equals sign nor a semicolon is used.

The Advantage of Constants


If your program has tow integer variables named students and classes, you could compute how many students you have, given a known number of classes. If you knew there were 15 students per class, the line would look like this: students = classes * 15; In this example, 15 is a literal constant. Your code would be easier to read, read and easier to maintain, maintain if you substituted a symbolic constant for this value: const unsignd int studentsPerClass = 15; students = classes * studentsPerClass; If you later decided to change the number of students in each class, you could do so where you define the constant g to make a change g every y studentsPerClass without having place you use that value!

Operators for Fundamental Data Types


Arithmetic Operators Adding Variables Subtracting Variables Multiplying Variables The Division Operator The Modulus Operator Memory Concept Rules of Operator Precedence Unsigned Data Types Which Type? Type Conversion Automatic Conversion Type Casting Compound Assignment Sign Operators Increment / Decrement Operators

Arithmetic Operators
An operator is a symbol that represents a specific action. Operators used for arithmetic are called arithmetic operators. operators

Operation

C++ Algebraic arithmetic expression operator


+ x+7 xy x y or x . y
x or x / y or x y y

C++ expression
x + 7 x - y x * y x / y x % y

Addition Subtraction Division Modulus

Multiplication * / %

x mod y

Adding Variables
If you want to add two variables, variables use the (+) symbol. symbol You can take the result and either print it or put it back into a variable. The following example adds two variables (start and time) and then prints the answer to the console:
#include <iostream.h> int main() { int start, start time; start = 37; time = 22; cout << start + time << endl; return 0; }

This code starts with two integer variables called start and time. It then sets start to 37, and time to 22. Finally, y, it adds the two variables (to get 59) and prints the result.

In this example, however, the computer doesnt actually do anything with the final sum, 59, except print it. If you want to use this value later, you can save it in its own variable. The following code demonstrates this:
#include <iostream.h> int main() { int start, time, total; start = 37; time = 22; total = start + time; cout << total << endl; return 0; 0 }

In this code, code we declared the integer variable total along with the others. Then, after we stored 37 in start and 22 in time, we added the two and saved the sum in the variable total. Then we finally printed the value stored in total.

You can also add numbers themselves to variables. The g line adds 5 to start and p prints the result. following
cout << start + 5 << endl;

Or, you can save the value back in another variable, Or variable as in the following fragment:
total = start + 5; cout << total << endl;

This adds 5 to start and saves the new value in total. When you use such code as total = start + 5;, although you are adding 5 to start, you are not actually changing the value stored in start. The start variable itself remains the , the same as it was before this statement runs. Rather, computer figures out the result of start + 5 and saves that value inside total. Thus, total is the only variable that changes here.

Now heres where things get a little tricky in the logical arena This might seem a strange at first, arena. first but you can actually do something like this:
t t l = t total total t l + 5; 5

You might find this statement a little bizarre. But remember, total is a variable in computer programming, and that definition is a bit different from in the math world. This statement really just means were going to add 5 to the value stored in total, and well take the value we get back and store it back in total. In other words, total will now be 5 greater than it was to begin with. The following code shows this in action:

#include <iostream> using namespace std; int main() { int total; total = 12; cout << total << endl; total = total + 5; cout << total << endl; return t 0 0; }

When you run this program, you see the following output on the console:
12 17

Note that cout and the << operator know how to treat numeric values and strings differently. If we send them a string, they print it as text. If we send them a variable or an operation, ti th they print i t it as a number. b

Subtracting Variables
Everything you can do involving addition of variables you can also do with subtraction. For example, you can subtract two variables, as shown in this program:
#include <iostream> int main() { int final, time; final = 28; time = 18; cout << final - time << endl; return 0; }

When this p program g runs, , the console shows the number 10. Remember that, as with addition, the value of neither final nor time actually changed. The computer just figured out th difference the diff and d printed i t d the th answer on the th console l without ith t modifying either variable.

You can also subtract a number from a variable, and (as ) y you still arent actually y changing g g the value of the before) variable, as in the following example:
cout << final - 5 << endl;

You can subtract one variable from another and save the result in a third variable:
start = final - time;

And you can change the value in a variable by using subtraction, as in the following sample lines of code. This first subtracts time from start and saves it back in start:
final = final - time;

Or y you can do the same thing g with a number:


final = final - 12;

Multiplying Variables
To do multiplication in C++, C++ you use the (*) symbol. symbol Like addition and subtraction, you can multiply two variables, or you can multiply a variable by a number. number You can take the result and either print it or save it in a variable. For example, F l you can multiply lti l two t variables i bl and d print i t the th results to the console with the following:
cout << length * width << endl;

Or you can multiply a variable by a number as in this:


cout << length * 5 << endl;

And d as with w t addition add t o and a d subtraction, subt act o , you can ca multiply u t p y two variables and save the result in a third variable:
area = length * width;

And you can use multiplication to modify a variables value, as in the following:
total = total * multiplier;

A d (as And ( b before) f ) you can d do th the same with ith j just t a number b
total = total * 25;

Sample Program: Circumference and area of a circle


#include <iostream.h> int main() { const double pi = 3.141593; 3 141593; double radius, circuit, area; cout << "Radius = "; cin >> radius; circuit = 2 * pi * radius; area = pi * radius * radius; cout << "Radius: Radius: " << radius << endl << "Circumference: " << circuit << endl << "Area: " << area << endl; return 0; }

Sample output
Radius = 1.5 Radius: 1.5 Ci Circumference: f 9 42478 9.42478 Area: 7.06858

As we mentioned before, declarations of variables can be placed almost anywhere p y in a p program, g , but they y must appear pp before their corresponding variables are used in the program.
# #include <iostream.h> int main() { const double pi = 3.141593; 3 141593; cout << "Radius = "; double radius; cin >> radius; double circuit; circuit = 2 * pi * radius; d bl area; double area = pi * radius * radius; cout << "Radius: " << radius << endl << "Circumference: " << circuit << endl << "Area: " << area << endl; return 0; }

The Division Operator


Although addition, addition subtraction, subtraction and multiplication are pretty straightforward with integer variables, division is a bit trickier. The chief reason is that, with whole numbers, sometimes you just cant divide evenly. Its like trying to divide 21 tortilla chips evenly between 5 people. You just cant do it. Either somebody will feel cheated, or everyone will get 4, and 1 chip will be left. The behavior of the division operator depends on the type of the operands. If both operands are integers, C++ performs i t integer division. di i i That Th t means any fractional f ti l part t of f the th answer is discarded, making the result an integer. If one or both operands are floating-point values values, the fractional part is kept, making the result floating-point. The following program p g illustrates how C++ division works with different types of values.

// integer and floating-point division #include <iostream.h> <iostream h> int main() { cout << fixed; cout << "Integer division: 9/5 = "; cout << 9 / 5 << "\n"; \n ; cout << "Floating-point division: 9.0/5.0 = "; cout << 9.0 / 5.0 << "\n"; cout << "Mixed division: 9.0/5 / = "; cout << 9.0 / 5 << "\n"; cout << "double constants: 1e7/9.0 / = "; ; cout << 1.e7 / 9.0 << "\n"; cout << "float constants: 1e7f/9.0f = "; co t << 1.e7f cout 1 e7f / 9.0f 9 0f << "\n" "\n"; return 0; }

Output
Integer division :9/5 = 1 Floating-point division: 9.0 / 5.0 = 1.800000 Mixed division: 9.0 / 5 = 1.800000 d bl constants: double t t 1 7/9 0 = 1111111.111111 1e7/9.0 1111111 111111 float constants 1e7/9.0 = 1111111.125000

The fi Th first t output t t li line shows h th that t dividing di idi th the integer i t 9 by b the th integer 5 yields the integer 1. The fractional part 0.8 is discarded The next two lines show that when at least one of discarded. the operands is floating-point, you get a floating-point answer of 1.8. Actually, when you try to combine mixed types, C++ converts all the concerned types to the same type. The relative precisions of the last two lines show that the result is type double if both operands are double and that it is float if both operands are float. Remember, floatingpoint i t constants t t are type t double by b default. d f lt

The Modulus Operator


There is a fifth arithmetic operator that works only with integer variables. Its called the modulus operator, and is p by y %, , the p percent symbol. y This operator p finds the represented remainder when one number is divided by another. The following program demonstrates the effect.
// demonstrates modulus operator #include <iostream.h> int main() { cout << 6 % 8 << endl // 6 << 7 % 8 << endl // 7 << 8 % 8 << endl // 0 << 9 % 8 << endl dl // 1 << 10 % 8 << endl; // 2 return 0; }

Here the numbers 6 through 10 are divided by 8, using the p The answers are 6, 7, 0, 1, and 2the remainder operator. remainders of these divisions. The modulus operator is used in a wide variety of situations. Note

Attempting p g to use the modulus operator p (%) with noninteger g operandsisacompilationerror.

Memory Concepts
Variable names such as number1, number2 and sum actually correspond to locations in the computer's memory. Every , a type, yp , a size and a value. variable has a name, In the previous program, when the statement
cin >> number1;

is executed, the number typed by the user is placed into a memory y location to which the name number1 has been assigned by the C++ compiler. Suppose the user enters the number 45 as the value for number1. The computer will place 45 into location number1, number1
45

Whenever a value is placed in a memory location, the value overwrites the previous value in that location; thus, thus placing a new value into a memory location is said to be destructive.

Returning to our addition program, when the statement


cin >> number2;

is executed, suppose the user enters the value 72. This value is placed into location number2, and memory appears as in the figure. Note that these locations are not necessarily j in memory. y adjacent number1 number2
45 72

Once the program has obtained values alues for number1 b 1 and number2, it adds these values and places the sum into variable sum. The statement
sum = number1 + number2;

that performs the addition also replaces whatever value was stored in sum.

This occurs when the calculated sum of number1 and number2 is p placed into location sum ( (without regard g to what value may already be in sum; that value is lost). After sum is calculated, memory appears as in the figure. number1 number2 sum
45 72 117

Note that the values of number1 and number2 appear exactly as they did before they were used in the calculation of sum. These values were used, but not destroyed, as the computer performed the calculation. calculation Thus, Thus when a value is read out of a memory location, the process is nondestructive.

Rules of Operator Precedence


1.

Operators O t in i expressions i contained t i d within ithi pairs i of f parentheses are evaluated first. Parentheses are said to be at the "highest highest level of precedence precedence". In cases of nested nested, or embedded, parentheses, such as ((a+b)+c) the operators in pair of p parentheses are applied pp first. the innermost p Multiplication, division and modulus operations are applied p contains several multiplication, p , next. If an expression division and modulus operations, operators are applied from left to right. Multiplication, division and modulus have the same level of precedence. Addition and subtraction operations are applied last. If an expression contains several addition and subtraction operations, operators are applied from left to right. Addition and d subtraction bt ti also l have h the th same level l l of f precedence. d

2.

3.

for example: x = 1 + 3 * 2 3 * 2 is executed first, and then 1 is added, resulting in the number 7. 7 Parentheses increase the order of precedence. If you take the preceding formula and add parentheses, as shown here x = (1 + 3) * 2 1 + 3 executes first first, producing 4, 4 which is multiplied by 2, 2 resulting in 8. When we say that certain operators are applied from left to right, we are referring to the associativity of the operators. For p , in the expression p example, x = a + b + c the addition operators (+) associate from left to right, so a + b is calculated first, then c is added to that sum.

The following example contains modulus (%), multiplication, division addition division, addition, subtraction and assignment operations: Algebra: C++: z = p r mod q + w / x - y z = p * r % q + w / x - y
6 1 2 4 3 5

The circled numbers under the statement indicate the order in which C++ applies the operators. The multiplication, modulus and division are evaluated first in left-to-right order because they have higher precedence than addition and subtraction. The addition and subtraction are applied next. These are also applied left to right. right Then the assignment operator is applied.

Sample Program
// Average of two numbers #include <iostream.h> int main() { double x, y; cout << "Enter Enter two floating-point floating point values: "; ; cin >> x >> y; cout << "The average of the two numbers is: " << (x ( + y)/2.0 )/2 0 << endl; return 0; }

Sample output
Enter two floating-point values: 4.75 12.3456 The average of the two numbers is: 8.5478

Unsigned Data Types


By eliminating the sign of the integer types, types you can change their range to start at 0 and include only positive numbers. This allows them to represent numbers twice as big as the signed type. Look at this program:
# #include <iostream.h> int main() { int signedVar = 1500000000; unsigned int unsignVar = 1500000000; signedVar = (signedVar * 2) / 3; unsignVar = (unsignVar * 2) / 3; cout << "signedVar = " << signedVar << endl; cout << "unsignVar = " << unsignVar << endl; return 0; }

Heres the output: signedVar = -431655765 431655765 unsignVar = 1000000000 The signed g variable displays p y an incorrect answer, , while the unsigned variable, which is large enough to hold the intermediate result of the multiplication, records the result correctly. tl The Th program multiplies lti li both b th variables i bl by b 2, 2 then th divides them by 3. Although the result is smaller than the original number, number the intermediate calculation is larger than the original number. This is a common situation, but it can lead to trouble. We expect that two-thirds the original value, or 1,000,000,000, will be restored to both variables. Unfortunately, in signedVar the multiplication created a result3,000,000,000 3 000 000 000that exceeded the range of the int variable (2,147,483,648 to 2,147,483,647). The moral is this: Be careful that all values generated in your program are within the range of the variables that hold them.

Which Type?
With this richness of C++ integer types, types which should you use? Generally, int is set to the most "natural" integer size for the target computer. Natural size means the integer form the computer handles most efficiently. If there is no compelling reason to choose another type, use int. Now look at reasons why you might use another type. If a variable represents something that never is negative, such as the number of words in a document, you can use an unsigned type; that way the variable can represent higher values. Using short can conserve memory. Most typically, this is important only if you have a large array of integers. (An array is i a data d t structure t t that th t stores t several l values l of f the th same type sequentially in memory.) If it is important to conserve space, space you should use short instead of int.

Type Conversion
C++, like C, C++ C is more forgiving than some languages in the way it treats expressions involving several different data types. As an example, consider the following program:
#include <iostream.h> int main() { int count = 7; float avgWeight = 155.5; double totalWeight = count * avgWeight; cout << "totalWeight=" << totalWeight << endl; return 0; ; }

Here a variable of type yp int is multiplied p by y a variable of type yp float to yield a result of type double. This program compiles without error; the compiler considers it normal th t you want that t to t multiply lti l numbers b of f diff different t t types (or ( perform any other arithmetic operation).

Not all languages are this relaxed. Some dont permit MIXED expressions, expressions and would flag the line that performs the mixed-type arithmetic as an error. Such languages assume that when you mix types youre you re making a mistake mistake, and they try to save you from yourself. C++ and C, however, assume that you must have a good reason for doing what youre doing, and they help carry out your intentions. This is one reason for the popularity of C++ and C. C They give you more freedom. Of course, with more freedom, theres also more opportunity for you to make a mistake. mistake

Automatic Conversions
Let s consider what happens when the compiler confronts Lets such mixed-type expressions. Types are considered higher or lower, lower, based roughly on the order shown in this Table:

Data Type yp
double float long int short char

Order
Highest

Lowest

The arithmetic operators like to operate on two operands of the same type type. When two operands of different types are encountered in the same expression, the lower-type variable is converted to the type of the higher-type variable variable. Thus the int value of count is converted to type float and stored in a temporary variable before being multiplied by the float variable avgWeight. The result (still of type float) is then converted to double so that it can be assigned to the double variable totalWeight. These conversions Th i t take k place l i invisibly, i ibl and d ordinarily di il you dont need to think too much about them; C++ automatically d does what h t you want. t

Type Casting
You might find it necessary at times to convert from one variable type to another. For example from floating-point numbers to integers and vice versa. In C++, this conversion is easy: You just copy one to the other, and C++ takes care of the rest. Th only The l catch t hi is th that t when h C++ C converts t from f a floatingfl ti point to an integer, it always truncates. It doesnt round up. When it converts 5.99 to an integer, it doesn doesnt t go up to 6; it goes down to 5. But theres an easy trick if you want to round it up: Add 0.5 to the number before you convert it. If you add .5 to 5.99, you first get 6.49, and then when you convert that, you get 6. G i the Going th other th direction di ti is i even easier: i To T convert t an integer i t to a floating-point data type, you just copy it. If i is an int, and d is a double, you just set it as follows to convert it: f = i;

Whenever you convert from a floating-point to an integer or y g to a floating-point, gp , y you must tell the from an inyeger compiler that you know what youre doing by adding (int) or (float) or (double) in front of the variable. Adding these keywords is called type casting. For example, the following tells the compiler that you know youre converting from a float to t an int:
float pi = 3.14159; i t roundedPi int d dPi = (i (int) t) pi; i

If you leave the (int) part out, the compiler displays a warning arning like this one: warning:conversionfromfloattoint,possiblelossofdata The type casting comes in two forms:
(typeName yp ) value //converts value to typeName yp type yp typeName (value) //converts value to typeName type

Example We know that the value of the division operation depends on whether at least one of the operands is a floating point data type. For example, the value of 10/4 is 2.5. However, in C++, when both operands are an integer (or other whole number data type), then the result is an integer as well, and th remainder the i d is i not t part t of f the th quotient. ti t This Thi is i true t even if the result is assigned to a floating point variable. The output of the following program is 10 / 4 = 2.
#include <iostream.h> int main() { int firstOp = 10, secondOp = 4; float result = firstOp p / secondOp; p; cout << firstOp << " / " << secondOp << " = " << result; return 0; }

However, the value of 10.0/4 is 2.5 in C++. When at least p is a floating gp point data type, yp , and 10.0 one of the operands would be interpreted as floating point, then the result is a floating point as well. The output of the following program is 10 / 4 = 2.5 because we changed the data type of firstOp from int to float:
#include <iostream.h> int main() { float firstOp = 10, result; int secondOp = 4; result = firstOp / secondOp; cout << firstOp << " / " << secondOp << " = " << result; return 0; }

Going back to the first example, if you want the result of the g variables to be a float, then y you have division of two integer to cast one of the variables to a float. A cast does not change the data type of the variable, just the data type of the value of the variable during the completion of the operation. You cast the variable by putting the desired data type in front of it in an expression, expression and placing either the desired data type or the variable in parentheses. This is how the first example could g to make the result of integer g division a float: be changed
#include <iostream.h> int main() { int firstOp = 10, secondOp = 4; float result = (float) firstOp / secondOp; cout << firstOp << " / " << secondOp << " = " << result; return 0; ; }

All of the following expressions would work


float fl t float float float result lt result result result = = = = (fl (float) t) fi firstOp tO / secondOp; dO float (firstOp) / secondOp; firstOp p / ( (float) ) secondOp; p firstOp / float (secondOp);

Compound Assignments
The great Th t makers k of f the th C++ language l gave us a bit of f a shortcut for adding a value to a variable and storing it back in the variable. variable The line
total = total + 5;

is the same as
total += 5;

This compact Thi tf form of f combining bi i arithmetic ith ti and d assignment i t operators perform simultaneously an addition and an assignment and it is not limited to the addition operator. assignment, operator It also can be used with the other arithmetic operators.

Statement
a = a + 2; a = a - 2; a = a * 2; a = a / 2; a = a % 2; Examples: x += 3; x -= y; x *= y + 2;

Compound Operators
a += 2; a -= 2; a *= 2; a /= 2; a %= 2;

is equivalent to is equivalent to is equivalent to

x = x + 3; x = x - y; x = x * (y+2);

Sample Program
#include <iostream.h> int main() { int x, x y; cout << "Please enter a starting value: "; cin >> x; cout t << "Pl "Please enter t th the i increment t value: l " "; cin >> y; x += y; // x = x + y cout << "Please enter a factor: "; cin >> y; x *= y; // x = x * y cout << "Please enter a divisor: "; cin >> y; x / /= y; // x = x / y cout << "And this is your lucky number: " << x << endl; return 0; }

Sample output
Please enter a starting value: 10 Please enter the increment value: 5 Please enter a factor: 2 Please enter a divisor: 4 And this is your lucky number: 7

Sign Operators
The sign operator () returns the value of the operand but inverts the sign. Example:
int n = 5; cout << n; // Output: -5 cout << -n; // Output: 5

The sign operator (+) performs no useful operation, simply returning the value of its operand.

Increment / Decrement Operators


The i Th increment t operator t (++) modifies difi the th operand d by b adding ddi 1 to its value. Given that i is a variable, both i++ (postfix notation) and ++i (prefix notation) raise the value of i by 1. In both cases the operation i = i + 1 is performed. However, prefix (++) and postfix (++) are two different operators. The difference becomes apparent if ++i or i++ is part of a more complex expression: ++i i++ i is incremented first and the new value of i is then applied. the original value of i is applied before i is incremented.

The decrement operator () modifies the operand by reducing the value of the operand by 1. Prefix or postfix notation can be used with ().

Sample Program
#include <iostream.h> int main() { y g = 39, , y yourAge g = 39; ; int myAge cout << "I am: " << myAge << " years old.\n"; cout << "You are: " << yourAge << " years old\n"; myAge++; // postfix increment ++yourAge; // prefix increment cout << "One year passes...\n"; cout << "I I am: " << myAge << " years old.\n"; old.\n ; cout << "You are: " << yourAge << " years old\n"; cout << "Another year passes\n"; cout << "I I am: " << myAge++ << " years old old.\n \n"; ; cout << "You are: " << ++yourAge << " years old\n"; cout << "Lets print it again.\n"; cout << "I I am: " << myAge << " years old old.\n \n"; ; cout << "You are: " << yourAge << " years old\n"; return 0; }

Output:
I am: 39 years old You are: 39 years old One year passes I am: 40 years old You are: 40 years old A th Another year passes I am: 40 years old You are: 41 y years old Lets print it again I am: 41 years old You are: 41 years old

The C++ Mathematical Functions

The C++ Mathematical Functions


C++ d C defines fi a rich i h and d varied i d set t of f mathematical th ti l functions. f ti All the math functions require the header file <math.h>.

Note:
Throughout, all angles are in radians.

Function Description
fabs(x) absolute value of x fmod(x,y) remainder of x/y as a floating-point number

Example

fabs( 8.76) is 8.76 fabs(-8.76) fmod(2.6, 1.2) is 0.2 pow(2, 7) is 128 pow(x y) x raised to power y ( xy ) pow(x,y) pow(9, 0.5) is 3 sqrt(x) square root of x (x is a nonnegative value) sqrt(9.0) is 3.0 l (2 718282) is log(2.718282) i 1.0 10 log(x) natural logarithm of x (base e) log(7.389056) is 2.0 log10(10.0) g is 1.0 log10(x) logarithm of x (base 10) log10(100.0) is 2.0 exp(x) exp(1.0) is 2.71828 exponential function ex sin(x) i ( ) t i trigonometric t i sine i of fx sin(0.0) i (0 0) is i 0 cos(x) trigonometric cosine of x cos(0.0) is 1.0 tan(x) trigonometric tangent of x tan(0 0) is 0 tan(0.0) asin(x) arc sine of x (x must be in the range 1 to 1) asin(1.0) is 1.5708 acos(x) arc cosine of x (x must be in the range 1 to 1) acos(-1.0) is 3.1415 atan(x) arc tangent of x atan(1.55741) is 1

Sample programs
#include <iostream.h> <iostream h> #include <math.h> int main() { double x = 2.5, y; y = pow(x, 3.0); cout << "2.5 raised to the power 3 yields: " << y << endl; cout << "2 2 + (5 raised to the power 2.5) 2 5) yields: " << 2.0 + pow(5.0, x) << endl; return 0; }

Output
2.5 raised to the power 3 yields: 15.625 2 + (5 raised to the power 2.5) yields: 57.9017

#include <iostream.h> #include <math.h> int main() { double angle, dsin, dcos, dtan; cout << "Please enter an angle in degrees: "; cin >> angle; angle = angle * 3.141593 / 180; dsin = sin(angle); dcos = cos(angle); dtan = tan(angle); cout << "Your angles trigonometric functions are:\n"; cout << " Sine is: " << dsin << endl; ; cout << " Cosine is: " << dcos << endl; cout << " Tangent is: " << dtan << endl; return 0; }

Sample output
Please enter an angle in degrees degrees: 30 Your angles trigonometric functions are: Sine is: 0.5 Cosine is: 0.866025 Tangent is: 0.57735

Making Decisions
The Th R Relational l ti lO Operators t Relational Expressions Relational Expressions and Characters Precedence of Relational Operators Selection Statement (if Statement) Double-Selection Statement (ifelse Statement) Conditional Operator (?:) The else-if Chains Multiple-Selection Statement (switch Statement) Nested if Statements Logical Operators

The Relational Operators


We make W k comparisons i all ll the th time, ti and d so do d programs. A program may need to determine whether one value is equal to greater than, to, than or less than another value. value Operator < <= > >= == != Significance less than less than or equal to greater than greater than or equal to equal to not equal to

Relational Expressions
Relational operators compare two operands. operands A statement with two operands and a relational operator between them is called a relational expression. The result of a relational expression is a boolean value, true or false, where true means that the comparison is correct and false means that the comparison is not correct.
Example: p length == circuit // false or true

If the variables length and circuit contain the same number, the comparison is true and the value of the relational expression is true. But if the expressions contain different values, the value of the expression will be false.

Examples for Relational Expressions Relational Expression


4 == 4 4 < 4 4 <= 4 4 > 4 4 != 4 4 == 5 4 < 5 4 <= 5 4 > 5 4 >= 5 4 != 5 Value true false true false false false true true false false true

Relational Expressions and Characters


When individual Wh i di id l characters h t are compared, d the th character h t codes are compared. The result therefore depends on the character set you are using. using The following expression results in the value true when ASCII code is used. E Example: l 'A' < 'a' // true, since 65 < 97

Precedence of Relational Operators


Relational operators have lower precedence than arithmetic operators but higher precedence than assignment operators.

Precedence High

Operator p arithmatic operators < <= == > ! != >=

Low

assignment operator

Examples for comparisons


Comparison 4+2 == 5 2*4 != 7 Result false true

Example: , max; ; int index, bool flag = index < max 1; In our example, max 1 is evaluated first, then the result is p to index, , and the value of the relational expression p compared (false or true) is assigned to the flag variable. Example: int x, length, limit; length = x + 1 == limit; In this example x + 1 is evaluated first, then the result is compared to limit, and the value of the relational expression is assigned to the length variable. Since length is an int type, a numerical value is assigned instead of false or true, i.e. i e 0 for false and 1 for true.

It is quite common to assign a value before performing a comparison, and parentheses must be used in this case. Example: (length = x + 1) == limit This example stores the result of x + 1 in the variable length and then compares this expression with limit. Note
You cannot use the assignment operator (=) to compare two expressions The compiler will not generate an error message if expressions. the value on the left is a variable. This mistake has caused headaches for lots of beginners when troubleshooting their programs.

Selection Statement (if Statement)


The if statement allows you to put some decision-making decision making into your programs. The general form of the if statement is: if (condition diti )

statement;
If the condition is true (nonzero), (nonzero) the statement is executed. executed If the expression is false (zero), the statement is not p , suppose pp the p passing gg grade on an exam executed. For example, is 60. In C++ this is written as: if (grade >= > 60) cout << "Passed"; If the condition (g (grade >= 60) ) is true, then "Passed" is printed and the next statement in order is performed. If the condition is false, the print statement is ignored and the next statement in order is performed.

Multiple statements after the if may be grouped by putting them inside curly braces ({ }). ) The general form is:
if (condition) {

statement1; statement2;
... }

Example: E l cout << "Do you want to play again (Y/N)?: "; char answer; cin >> answer; if (answer == 'Y') { life = 5; points = 0; p ; }

Sample program
#include <iostream.h> int main() { int number1, , number2; ; cout << "Enter two integers to compare: "; cin >> number1 >> number2; if (number1 == number2) cout << number1 << " == " << number2 << endl; if (number1 != number2) cout << number1 << " ! != " << number2 << endl; if (number1 < number2) cout << number1 << " < " << number2 << endl; if (number1 > number2) cout << number1 << " > " << number2 << endl; if (number1 <= number2) cout << number1 << " <= " << number2 << endl; if (number1 >= number2) cout << number1 << " >= " << number2 << endl; return 0; }

Sample output
Enter two integers to compare: 3 7 3 != 7 3 < 7 3 <= 7

Sample output
Enter two integers to compare: 22 12 22 != 12 22 > 12 22 >= 12

Sample output
Enter E t t two i integers t t to compare: 7 7 7 == 7 7 <= 7 7 >= 7

Double-Selection Statement (ifelse Statement)


The if single-selection single selection statement performs an indicated action only when the condition is true; otherwise the action is skipped. The if...else double double-selection selection statement allows the programmer to specify an action to perform when the condition is true and a different action to perform when the condition is false. The general form of the if...else statement is:
if (condition)

statement;
else l

statement;
If the condition is true t , the first statement is executed. executed If it is false, the second statement is executed.

The preceding "passing grade" example can be written as:


if (grade >= 60) cout << "Passed"; else cout << "Failed";

This code prints "Passed" if the student's grade is greater than or equal to 60, but prints "Failed" if the student's grade is less than 60. In either case, after printing occurs, the next code d statement in i sequence is i performed. f d Multiple statements after the if and after the else may be grouped db by putting tti them th inside i id curly l braces b ({ }). )

Sample program The following program tests if a whole number entered by the user is even or odd:
#include <iostream.h> <iostream h> int main() { int num; cout << "Enter a whole number: "; cin >> num; u % 2 == 0 ) if ( num cout << "The number is even" << endl; else cout << "The number is odd." << endl; ; return 0; }

Sample output
Enter a whole number: 17 The number is odd.

Conditional Operator (?:)


C++ provides the conditional operator (?:), which is closely related to the if...else statement. The conditional operator is C++'s only ternary operator, it takes three operands. The operands, together with the conditional operator, form a conditional expression. The first operand is a condition, the second operand is the value for the entire conditional expression i if the h condition di i i is true and d the h third hi d operand d is i the value for the entire conditional expression if the condition is false. i

For example, the output statement cout << ( grade d >= 60 ? "Passed" d : "Failed" il d ) ); contains a conditional expression grade >= 60 ? "Passed" : "Failed" g "Passed" if the condition that evaluates to the string grade >= 60 is true, but evaluates to the string "Failed" if the condition is false. Thus, the statement with the conditional operator performs essentially the same as the preceding if...else statement. The precedence of the conditional operator is low, so the parentheses in the preceding expression are required.

The else if Chains


The ifelse statement involved only two alternatives. alternatives Additionally, only one could be chosen, not both. A whole number is either even or odd; ; it cant be both and there is no third alterative. There are situations where there are more than two alternatives. For example, if you take a test, your grade may be one of five types: A, B, C, D, or F. Additionally, you cant get an A and a C on the same test. Since you can h Si have only l one if expression i and d only l one else expression in an ifelse statement, you need another expression for the third and additional alternatives. alternatives That expression is else if. You use the else if chain when there are three or more alternatives. gp program g shows the else if chain in a p program g The following that determines your grade based on your test score.

Sample program
#include <iostream.h> int main() { int testScore; cout << "Enter your test cin >> testScore; if (testScore >= 90) cout << "Your grade is else if ( (testScore >= 80 cout << "Your grade is else if (testScore >= 70 cout << "Your Your grade is else if (testScore >= 60 cout << "Your grade is else cout << "Your grade is return 0; }

score: ";

an A\n"; ) a B\n"; ) a C\n"; C\n ; ) a D\n"; an F\n";

Sample outputs
Enter your test score: 77 Your grade is a C Enter your test score: 91 Your grade is an A Enter your test score: 55 Your grade is an F

Multiple-Selection Statement (switch Statement)


The switch statement Th t t t allows ll you to t choose h between b t multiple lti l alternatives, it compares the value of one expression with multiple constants. constants The general form of a switch statement is:
switch (expression) { case const1: statement; break; case const2: statement; break; . . . [default: statement;] }

The case statements can be in any order. The constants must be different and can only be integral types (boolean values and character constants are also integral types). The default d f lt statement can be put anywhere in the switch it h. When C++ sees a switch statement, it evaluates the expression i and d then th looks l k for f a matching t hi case statement. t t t If none is found, the default statement is used. If no default is found found, the statement does nothing nothing. A break statement inside a switch tells the computer to continue ti the th execution ti after ft the th switch it h. If the th break b k is i not t there, execution continues with the next statement. The f Th following ll i program shows h a switch statement t t t in i a program that determines your average based on your grade.

Sample program
#include <iostream.h> int main() { char grade; cout << "Enter Enter your grade (A, B, ...): ): "; ; cin >> grade; switch (grade) { case 'A': 'A' cout << "Your average must be between 90 break; case 'B': B : cout << "Your average must be between 80 break; case 'C': co t << "Yo cout "Your r a average erage m must st be bet between een 70 break; case 'D': cout << "Your average g must be between 60 break; default: cout << "Your average must be below 60\n"; } return 0; }

100\n"; 89\n"; 79\n" 79\n"; 69\n"; \ ;

Sample outputs
Enter your grade d ( (A, B, ...): ) C Your average must be between 70 - 79 Enter your grade (A, B, ...): A Your average must be between 90 - 100 Enter your grade (A, B, ...): F Your average must be below 60

Nested if Statements
An if statement may appear inside another if statement. When this is done, the inner if statement is said to be nested t d i inside id the th outer t if statement. t t t You can nest if statements to determine if both of two b l boolean expressions i are true, or if either i h of f the h expressions i is true.

Example: Testing if Both Boolean Expressions Are true


The following program shows the use of nested if statements in determining if both of two boolean expressions are true. If the user users s input is that they are at least 18 years old and a citizen, the program outputs that they are eligible to vote. Otherwise the program outputs that they are not eligible to Otherwise, vote.

#include <iostream.h> int main() { int age; char choice; bool citizen; cout << "Enter Enter your age: "; ; cin >> age; cout << "Are you a citizen (Y/N): "; cin >> choice; ; if (choice == 'Y') citizen = true; else citizen = false; if (age >= 18) if (citizen == true) cout << "You are eligible to vote"; else cout << "You are not eligible to vote"; else cout << "You are not eligible to vote"; return 0; }

Sample outputs
Enter your age: 18 Are you a citizen (Y/N): Y You are eligible g to vote Enter your age: 25 Are you a citizen (Y/N): N You are not eligible to vote Enter your age: 17 Are you a citizen (Y/N): Y You are not eligible to vote Enter your age: 17 Are you a citizen (Y/N): N You are not eligible to vote

Example: Testing if Either Boolean Expression Is true


The following program shows the use of the nested if statements in determining if either of two boolean expressions are true. true If the user users s input indicates that they are either no more than 12 years old or at least 65 years old, the program outputs that their admission is free. Otherwise, the program outputs that they have to pay.

#include <iostream.h> int main() { int age; cout << "Enter your age: "; cin >> age; if (age ( > 12) if (age >= 65) cout << "Admission is free"; else cout << "You have to pay"; else cout << "Admission is free"; return 0; }

Sample outputs
Enter your age: 12 Admission is free Enter your age: 13 You have to pay Enter your age: 65 Admission is free

Logical Operators
Multiple M lti l relational l ti l expressions i may be b grouped d together t th with ith logical operators. C++ has logical operators that enable you to combine comparisons in one if or ifelse statement. statement Operator && Name and What It Does
Connects two relational expressions. Both expressions must be true for the overall expression i t to be b true. Connects two relational expressions. If either ith expression i i is true t , the th overall ll expression is true. Reverses the truth of an expression, expression making a true expression false, and a false expression true.

||

or

not

The Logical (and) Operator


E Expression i 1 E Expression i 2 E Expression i 1 && Expression E i 2

true true false false

true false true false

true false false false

The Logical (or) Operator


Expression 1 Expression 2 Expression 1 && Expression 2

true true false false

true false true false

true true true false

The following program shows the use of the logical (and) operator in determining whether the user is eligible to vote, th criteria the it i being b i th that t the th user must t be b at t least l t 18 years old ld and a citizen.
#include <iostream.h> <iostream h> int main() { int age; char choice; bool citizen; cout << "Enter your age: "; cin >> age; cout << "Are y you a citizen ( (Y/N)?: / ) "; ; cin >> choice; if (choice == 'Y') citizen = true; ; else citizen = false; if (age g >= 18 && citizen == true) cout << "You are eligible to vote"; else cout << "You are not eligible to vote"; return 0; }

Sample program The following program shows the use of the logical (or) operator in determining whether you get into a movie free, g that the user must be either no more than the criteria being 12 or at least 65 years old.
#include <iostream.h> <iostream h> int main() { i t age; int cout << "Enter your age: "; cin >> age; if (age <= 12 || age >= 65) cout << "Admission is free"; else cout << "You have to pay"; return 0; }

Iteration Statements

The for Loop The while Loop p The do-while Loop When to Use Which Loop The break And continue Keywords Nested Loops

Iteration statements (loops) are control structures that cause a section ti of f your program t to be b repeated t d a certain t i number b of f times. The repetition continues while a condition is true. Wh When th the condition diti b becomes false f l , th the loop l ends d and d control passes to the statements following the loop. There are three kinds of loops in C++: the for loop, the while loop, and the do-while loop.

The for Loop


The for Th f l loop executes t a section ti of f code d a fixed fi d number b of f times. Its usually used when you know, before entering the loop how many times you want to execute the code loop, code. The general form of the for loop is:
for (initialization; condition; increment) statement;

or:
for (initialization; condition; increment) { statement1; statement2; statement3;

...
}

The for statement consists of the keyword for, followed by parentheses that contain three expressions separated by semicolons. The body Th b d of f the th loop l is i the th code d to t be b executed t d each h time ti through the loop. Repeating this code is the reason for the loop. Note that the for statement is not followed by a semicolon. Thats because the for statement and the loop body are together considered to be a program statement. This is an important detail. If you put a semicolon after the for statement, the compiler will think there is no loop body, and the program will do things you probably dont expect. Lets see how the three expressions in the for statement control the loop.

The Initialization Expression


The initialization expression is executed only once, once when the loop first starts. It gives the loop variable an initial value.

Th C The Condition diti Expression E i


The condition expression usually involves a relational operator. It is evaluated each time through the loop, just before the body of the loop is executed. It determines whether the loop will be executed again. If the test expression is true, the loop is executed one more time. If its false, the loop ends, d and d control l passes to the h statement f following ll i the h l loop.

The Increment Expression


The increment expression changes the value of the loop variable, often by incrementing it. It is always executed at the end of the loop, after the loop body has been executed.

Sample program
#include #i l d <iostream.h> i t h int main() { int counter; for (counter=0; counter<15; counter++) cout << counter * counter << " "; cout << endl; return 0; }

Output
0 1 4 9 16 25 36 49 64 81 100 121 144 169 196

Sample program
// calculates factorials #include <iostream.h> int main() { unsigned int numb, fact; cout << "Enter a number: "; ; cin >> numb; fact = numb; for (int j=numb-1; j=numb 1; j>0; j j--) ) fact *= j; cout << "Factorial is: " << fact << endl; return 0; }

Output Enter a number: 10 Factorial t i l i is: 3628800

The while Loop


The for loop does something a fixed number of times. times What happens if you dont know how many times you want to do g before y you start the loop? p In this case a different something kind of loop may be used: the while loop. A while statement repeatedly executes a target statement as long as a condition is true. Its general form is:
while (condition) statement;

or: while (condition) { statement1; statement2; statement3; ... }

The next example asks the user to enter a series of numbers. p terminates. Notice When the number entered is 0, the loop that theres no way for the program to know in advance how many numbers will be typed before the 0 appears; thats up to the user.
#include <iostream.h> int main() { int n = 1; while (n != 0) { cout << "Enter a number (0 to exit): "; cin >> n; } cout << endl; return 0; }

Heres some sample output. The user enters numbers, and the p continues until 0 is entered, , at which p point the loop p and loop the program terminate.
Enter Enter Enter Enter Enter Enter a a a a a a number number number number number number (0 (0 (0 (0 (0 (0 to to to to to to exit): exit): exit): exit): exit): exit): 5 27 33 145 9 0

Sample program
#include <iostream.h> <iostream h> int main() { int counter = 0; while (counter < 15) { cout << counter * counter << " "; counter++; } cout << endl; return 0; }

Output
0 1 4 9 16 25 36 49 64 81 100 121 144 169 196

The do-while Loop


In a while loop, I l th condition the diti expression i i is evaluated l t d at t th the beginning of the loop. If the condition is false, the loop body wont t be b executed t d at t all. ll In I some situations it ti this thi is i what h t you want. But sometimes you want to guarantee that the loop b d is body i executed t d at t least l t once. When Wh this thi is i the th case you should use the do-while loop, which places the test expression i at the h end d of f the h loop. l

The general form of the do-while loop is: do statement; while (condition); or:
do {

statement1; statement2; statement3;


... } while (condition);

Sample program
#include <iostream.h> <iostream h> int main() { int dividend, divisor; char ch; do { cout << "Enter dividend: "; cin >> dividend; cout << "Enter divisor: "; cin >> divisor; cout << "Quotient is " << dividend / divisor; cout << ", remainder is " << dividend % divisor; cout << "\nDo another? (y/n): "; cin >> ch; } while (ch != 'n'); return 0; }

Sample output
Enter dividend: 11 Enter divisor: 3 Quotient i i is 3, 3 remainder i d i is 2 Do another? (y/n): y Enter dividend: 222 Enter divisor: 17 Quotient is 13, remainder is 1 D another? Do th ? (y/n): ( / ) y Enter dividend: 32 Enter divisor: 8 Quotient is 4, remainder is 0 Do another? (y/n): n

Sample program
#include <iostream.h> <iostream h> int main() { int counter = 0; do { cout << counter * counter << " "; counter++; } while hil (counter ( t < 15); 15) cout << endl; return 0; }

Output 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196

When to Use Which Loop

The for loop Th l i appropriate is i when h you know k i advance in d how many times the loop will be executed. The while and d do-while hil loops l are used d when h you dont d t know k i in advance when the loop will terminate. The while loop is used when you may not want to execute the loop body even once, and the do-while loop when h youre sure you want t to t execute t the th loop l b d at body t least once.

The break And continue Keywords


Inside I id the th body b d of f any of f the th looping l i constructs t t for, while, or do-while, you can control the flow of the loop using b break k and d continue ti . break quits the loop without executing the rest of the statements t t t in i the th loop. l continue stops the execution of the current iteration and goes back to the beginning of the loop to begin a new iteration.

Sample program
#include <iostream.h> <iostream h> int main() { for (int t=0; t<100; t++) { if (t == 5) continue; if (t == 10) break; cout << t << " "; } return 0; }

Output
0 1 2 3 4 6 7 8 9

Sample program: Fibonacci numbers


Th The Fib Fibonacci i numbers b F0 , F1, F2 , F3, ... are d defined fi d b by th the equations F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2 For example, letting n = 2 in the third equation yields F2 = F2-1 + F2-2 = F1 + F0 = 0 + 1 = 1 y, with n = 3, , Similarly, F3 = F3-1 + F3-2 = F2 + F1 = 1 + 1 = 2 and with n = 4, F4 = F4-1 + F4-2 = F3 + F2 = 2 + 1 = 3 The first ten Fibonacci numbers are 0 1 1 2 3 5 8 13 21 34

The following program prints all the Fibonacci numbers up to an input limit: #include <iostream.h> int main() { unsigned int x = 0, y = 1, sum, limit; cout << "Enter a positive integer: "; cin >> limit; cout << "Fibonacci numbers < " << limit << ":\n0, 1"; while (true) { sum = x + y; if (sum > limit) break; cout << ", " << sum; x = y; y = sum; } cout << endl; return t 0 0; }

Sample Outputs
Enter a positive integer: 100 Fibonacci numbers < 100: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 Enter E t a positive iti i integer: t 1000 Fibonacci numbers < 1000: 0, , 1, , 1, , 2, , 3, , 5, , 8, , 13, , 21, , 34, , 55, , 89, , 144, , 233, 377, 610, 987

Nested Loops
Sample programs
// nested for loops #include <iostream.h> <iostream h> int main() { for (int i=1; i<=3; i++) { cout << "i i = " << i << endl; for (int j=1; j<=4; j++) { cout << " j = " << j << endl; } cout << "-------\n"; \ ; } return 0; }

Output
i = 1 j = 1 j = 2 j = 3 j = 4 ------i = 2 j = 1 j = 2 j = 3 j = 4 ------i = 3 j = 1 j = 2 j = 3 j = 4 -------

// nested while loops #include <iostream.h> int main() { int i, , j; i = 1; while (i <= 3) { cout << "i = " << i << endl; j = 1; while (j <= 4) { cout << " j = " << j << endl; j++; } cout << "-------\n"; i++; } return 0; }

Sample program
#include <iostream.h> <iostream h> int main() { for (int i=1; i<=3; i++) { for (int j=1; j<=4; j++) { f for (i t k=1; (int k 1 k<=5; k< 5 k++) cout << '*'; cout << endl; } cout << endl; } return 0; }

Output ***** ***** ***** *****


***** ***** ***** ***** ***** ***** ***** *****

Formatting and Manipulators

Output Signed Positive Numbers Precision Decimal Point Output In Fields Field Width Fill Characters Alignment

Output Signed Positive Numbers


When negative Wh ti numbers b are output t t as decimals, d i l the th output t t will always include a sign, but when positive numbers are output as decimals, decimals the output will not include a sign. sign You can use the showpos manipulator to output signed positive u be s. numbers.
cout << showpos << 123; // Output: +123

The other positive numbers are printed with their sign as well:
cout << 22; // Output: +22

The output of a positive sign can be canceled by the manipulator noshowpos:


cout << noshowpos << 123; // Output: 123

Floating-point numbers are displayed to six digits by default. Decimals are separated from the integral part of the number by a decimal point. Trailing zeroes behind the decimal point are not printed. If there are no digits after the decimal point, the decimal point is not printed (by default). Examples: cout << 1.0; // Output:1 cout << 1.234; // Output:1.234 cout << 1.234567; 1 234567 // Output:1.23457 1 23457 The last statement shows that the seventh digit is not simply truncated but rounded. Very large and very small numbers are displayed in exponential notation. Example: cout << 1234567.8; // Output:1.23457e+06

The standard settings can be modified in several ways. You can


change the precision, i.e. the number of digits to be output force output o tp t of the decimal decim l point poi t and d trailing tr ili g zeroes eroes specify the display mode (fixed point or exponential).

Precision
Both B th the th manipulator i l t setprecision() and d the th method th d precision() can be used to redefine precision to be used. Example:
cout << setprecision(3) << 12.34; // Output:12.3

or:
cout.precision(3); p ( ); cout << 12.34; // Output:12.3

Note that the header file iomanip.h iomanip h must be included when using the manipulator setprecision(). This also applies to all standard manipulators called with at least one argument.

Decimal Point
The manipulator Th i l t showpoint outputs t t th the decimal d i l point i t and d trailing zeroes. The number of digits being output (e.g. 6) equals the current precision. precision Example:
cout << showpoint << 1.0; // Output:1.00000

However, fixed point output with a predetermined number of decimal places is often more useful. In this case, you can use the fixed manipulator with the precision defining the number b of f decimal d i l places. l Th The d default f lt value l of f 6 is i assumed d in the following example. Example:
cout << fixed << 66.0; // Output:66.000000

Sample program
#include <iostream.h> <iostream h> int main() { double x = 12.0; 12 0; cout.precision(2); cout << "By default: cout << "showpoint: cout << "fixed: cout << "scientific: return 0; }

" " " "

<< << << <<

x << endl; showpoint << x << endl; fixed << x << endl; scientific << x << endl;

Output
By y default: showpoint: fixed: scientific: 12 12. 12.00 1 20e+001 1.20e+001

Sample program
#include <iostream.h> <iostream h> int main() { cout << "Before using showpoint" << endl << "9.9900 prints as: " << 9.9900 << << "9 9.9000 9000 prints as: " << 9.9000 9 9000 << << "9.0000 prints as: " << 9.0000 << << endl; cout << showpoint << "After using showpoint" << endl << "9.9900 9.9900 prints as: " << 9.9900 << << "9.9000 prints as: " << 9.9000 << << "9.0000 prints as: " << 9.0000 << return t 0 0; }

endl endl endl

endl endl endl;

Output
Before B f 9.9900 9.9000 9.0000 using i showpoint h i t prints as: 9.99 prints as: 9.9 p prints as: 9

After using showpoint 9.9900 prints as: 9.99000 9.9000 prints as: 9.90000 9.0000 prints as: 9.00000

Output In Fields
The << operator Th t can be b used dt to generate t f formatted tt d output t t in i fields. You can

specify if th the field fi ld width idth set the alignment of the output to right- or left-justified specify a fill-character with which to fill the field.

Field Width
The field width is the number of characters that can be written to a field. If the output string is larger than the field width, the output is not truncated but the field is extended. The output will always contain at least the number of digits specified as the field width. You can either use the width() method or the setw() manipulator to define field width. Example:
cout.width(6);

or:
cout << setw(6);

One special attribute of the field width is the fact that this a ue is s non-permanent: o pe a e t: t the e field ed w width dt specified spec ed applies app es to value the next output only. The default field width is 0.

Fill Characters
If a field is larger than the string you need to output, output blanks are used by default to fill the field. You can either use the fill() method or the setfill() manipulator to specify another fill character. The fill character applies until another character is defined. Example: cout << cout << cout << cout << Output: 12 00012 12 00012
setw(5) << 12 << endl; setfill('0') << setw(5) << 12 << endl; 12 << endl; setw(5) << 12 << endl;

Alignment
Output O t t to t fields fi ld is i normally ll right-aligned. i ht li d Th The other th options ti available are left-aligned and internal, which can be set by using the manipulators left and internal. The manipulator internal left-justifies the sign and rightjustifies the number within a field. j Example: int a = cout << << cout << Output: + 12 - 12345
12, b = -12345; 12 12345; internal << showpos setw(8) << a << endl; setw(8) << b << endl;

Sample program
#include <iostream.h> <iostream h> #include <iomanip.h> int main() { int x = 64, y = 512, z = 1024; cout << "Default is right justified:\n"; cout << setw(8) (8) << x << endl; dl cout << setw(8) << y << endl; cout << setw(8) << z << endl; cout << "\n\nUse left to left justify:\n"; cout << left << setw(8) << x << endl; cout << setw(8) ( ) << y << endl; ; cout << setw(8) << z << endl; cout << "\n\nUse right to right justify:\n"; cout << right << setw(8) << x << endl; cout << setw(8) << y << endl; cout << setw(8) << z << endl; return 0; }

Output
Default is right justified: 64 512 1024 Use left to left justify: 64 512 1024 Use right to right justify: 64 512 1024

Arrays
Working g with Arrays y One-dimensional Arrays Array Elements Using One-dimentsonal Arrays Storing Arrays in Memory No Bounds Checking Arrays Have Fixed Size Specifying an Array's Size with a Constant Example: Sorting an Array Initializing Arrays C-Strings Multidimensional Arrays Declaring Multidimensional Arrays Using Tow-dimensional Arrays Initializing Multidimensional Arrays

Working with Arrays


All the th variables i bl covered d in i earlier li chapters h t can store t only l one particular data type. If you want to store a second piece of information, information you must create another variable. variable For example, in a program to store ages for five persons you need the variables age1, age1 age2, age2 age3, age3 age4, age4 age5. But what happens when you have to store a long list of related data? It wouldnt wouldn t be convenient to create a new variable for every single piece of data. What if you have to work with thousands p y records? The task q quickly y would and thousands of employee become overwhelming. Fortunately, arrays are the solution. Arrays are a special group of variables that can hold many pieces of data and that all have the same data type yp and name, , but different values.

Arrays are common in programming because they let you deal easily with large numbers of related variables. variables For example, finding the minimum and maximum values or sorting array elements.

One-dimensional Arrays
Declaring Arrays
To use an array in a program, you first must declare the array The declaration specifies the array type, array. type the name of the array, and the size of the array. Following is the format of an a array a ay declaration: dec a at o :

type arrayName[arraySize];

The arraySize must be an integer constant greater than zero. For example, to tell the compiler to reserve 12 elements for double array c, use the declaration
double c[12]; // c is an array of 12 doubles

Memory can be reserved for several arrays with a single declaration. The following declaration reserves 100 elements for the integer array b and 200 elements for the integer array x.
int b[100], // b is an array of 100 integers x[200]; [200] // x i is an array of f 200 i integers t

Arrays can be declared to contain values of any data type. For example, an array of type char can be used to store a character string.

Array Elements
Each E hi individual di id l variable i bl within ithi an array i is called ll d an element. l t Each element has a particular index associated with it. An index is a number that indicates which element of the array you are accessing. The numbering of the index starts at zero. So if you have an array with five elements, So, elements the indexes will be 0, 1, 2, 3, and 4. That means first element = index 0 second element = index 1 third element = index 2 forth element = index 3 fifth element l t=i index d 4

Using One-dimensional Arrays


Accessing elements of an array is similar to creating an array. array Each element in an array acts as a separate normal variable. To access a particular element, you use the arrays array s name, followed by the index number within the subscripting operator. For o example, e a p e, if you dec declare a et the ea array ay
int myArray[10];

and you want to assign a value to the first element (index number 0) you do the following:
myArray[0] = 15;

or cin >> myArray[0]; c y ay[0]; If you want to display the value of the fourth element (index number u be 3), you do t the e following: o ow g: cout << myArray[3];

Sample program
// gets four ages from user, user displays them #include <iostream.h> int main() { int age[4]; for (int i=0; i<4; i++) { cout << "Enter an age: "; cin i >> age[i]; [i] } ; cout << endl; for (int j=0; j<4; j++) cout << "age[" << j << "] = " << age[j] << endl; return 0; }

Sample output
Enter Enter Enter Enter age[0] age[1] age[2] age[3] an an an an = = = = age: age: age: age: 44 16 23 68 44 16 23 68

Example: Averaging Array Elements


// average of weekss weeks s sales (6 days) #include <iostream.h> int main() { double sales[6]; //array of 6 variables int j; //loop variable cout << "Enter sales for 6 days\n"; for (j (j=0; 0; j<6; j++) cin >> sales[j]; double total = 0; for (j=0; j<6; j++) total += sales[j]; double average = total / 6; cout << "Average = " << average << endl; return 0; }

Sample output
Enter sales for 6 days 352.64 867 70 867.70 781.32 867.35 746.21 189.45 Average = 634.11

Storing Arrays in Memory


In C++, C++ all arrays consist of contiguous memory locations locations. The array elements reside next to each other in memory. The lowest address corresponds to the first element, and the highest address to the last element. For example, after this fragment is run, i t x[7]; int [7] for (int i=0; i<7; i++) cin >> x[i]; //user inputs: 10 8 35 42 4 57 86
x looks like this:

For a one-dimensional array, the total size of an array in bytes is here: i computed t d as shown h h totalbytes=numberofbytesintype numberofelements

No Bounds Checking
C++ performs f no bounds b d checking h ki on arrays; nothing thi stops t you from overrunning the end of an array. If this happens during an assignment operation, operation you will be assigning values to some other variables data, or even into a piece of the programs program s code. code In other words, words you can index an array of size N beyond N without causing any compile or run-time error messages, even though doing so will probably cause your program to crash. As the programmer, it is your job both y are large g enough g to hold what the to ensure that all arrays program will put in them and to provide bounds checking whenever necessary. For example, C++ will compile and run the following program p g even though g the array y myArray y y is being g overrun.

CAUTION:
Do not try the following example. example It might crash your system! // An incorrect program. Do Not Execute! #include <iostream.h> int main() { int myArray[10]; for (int i=0; i<100; i++) myArray[i] A [i] = i i; // E Error! ! array overrun return 0; }

In this case, the loop will iterate 100 times, even though myArray A i only is l ten t elements l t l long! ! Thi This might i ht cause important information to be overwritten, resulting in a program failure.

The most common wrong way to access an array is to read or y y[ ]. This is one integer g beyond y the write location myArray[10] end of the array (myArray[9]). Although its only one element beyond the end of the array, reading or writing this location is just as dangerous as using any other incorrect address.

CAUTION
A common beginning programming mistake is to assume the index of the last element of the array is equal to the number of y Since the first index in an array y must elements in the array. always be 0, the last index in an array must always be 1 less than the number of elements in the array. If you were counting ten numbers, starting at 1, the last element would be number 10. However, if you are starting at 0 instead of 1, then the last number would be 9, 9 not 10. 10

Why C++ does not provide boundary checks on arrays?


You might be wondering why C++ does not provide boundary checks on arrays. The answer is that C++ was designed to give professional programmers the capability to create the fastest, most efficient code possible. Towards this end, virtually no runtime error checking is included because it slows (often dramatically) the execution of a program. Instead, C++ expects you, the th programmer, to t be b responsible ibl enough ht to prevent t array overruns in the first place and to add appropriate error checking on your own own, as needed needed.

Arrays Have Fixed Size


When you declare Wh d l an array, you tell t ll the th compiler il exactly tl h how many objects you expect to store in it. The compiler sets aside memory for f all ll the th objects, bj t even if you never use it. it This Thi i isnt t a problem with arrays for which you have a good idea of how man objects youll many oull need need. For e example, ample a chessboard has 64 squares. There is no operation to add elements to the array. Once we define an array array, we cannot add elements to it. it If we must add elements to the array, then we must manage th memory ourselves. the l W We have h to t ask k the th system t for f new storage to hold the larger array and copy the existing elements l t into i t that th t new storage. t We W do d that th t using i pointers. i t

Specifying an Array's Size with a Constant


Each E h of f the th size i declarators d l t used d in i the th arrays was a literal. lit l A literal is a value that is written exactly as it is meant to be interpreted For example, interpreted. example the number 3 is a literal. literal Its value cannot be anything other than 3. You cant change the number 3 to have some different value. value Accordingly, Accordingly the number 3 may be used in the following program as the size declarator:
#include <iostream.h> int main() { int testScore[3]; ... return 0; }

The size declarator may not be a variable. If a variable is uses as the size of the array, the compiler does not know how much memory to allocate because a variables value may change. Indeed, in the following example, the value of the variable used d as th the size i of f the th array is i not t even known k until til runtime: ti
#include <iostream.h> int main() { int numTests; co t << "Enter the n cout number mber of test scores scores:"; " cin >> numTests; int testScore[numTests]; // Error!!! return 0; }

The result is a compiler error. error The compiler will flag the declaration of the array (int testScore[numTests]) and complain p that a constant expression p was expected. p

A constant is the opposite of a variable, while a variable is a name that may represent different values during the execution of a program. However, the value of a constant cannot change during the execution of a program. You may use a constant instead of a literal as a size gp program g uses declarator. The size declarator in the following a constant for the value 3 rather than the literal 3:
#include <iostream.h> <iostream h> int main() { const int numTests = 3; int testScore[numTests]; ... ... return 0; }

Defining the size of each array as a constant variable instead of a literal constant can make programs more scalable. Defining the size of an array as a constant variable instead of a literal constant makes programs clearer. This technique eliminates so-called magic numbers. For example, repeatedly mentioning the size 10 in arrayprocessing code for a 10-element array gives the number 10 an artificial significance and can unfortunately confuse f the th reader d when h the th program includes i l d other th 10s 10 that have nothing to do with the array size.

Example: Minimum and Maximum Values in an Array


# #include <iostream.h> int main() { const t i int t SIZE = 9; 9 int list[SIZE], i, minValue, maxValue; for (i = 0; i < SIZE; i++) { list[i] = rand(); // random numbers 0..32767 cout << list[i] << " "; ; } // find minimum value minValue = list[0]; for (i = 1; i < SIZE; i++) { if (list[i] < minValue) minValue = list[i]; } cout << "\nminimum value: " << minValue << endl;

// find maximum value maxValue = list[0]; [ ] for (i = 1; i < SIZE; i++) { if (list[i] > maxValue) maxValue = list[i]; } cout << "maximum value: " << maxValue << endl; return 0; }

Output
41 18467 6334 26500 minimum value: 41 maximum value: 29358 19169 15724 11478 29358 26962

Example: Sorting an Array


Among the A th techniques t h i for f sorting ti an array is i the th bubble b bbl sort, t which programmers frequently use for sorting small arrays. The key Th k idea id of f the th bubble b bbl sort t is i t to compare adjacent dj t elements in the array. Begin by comparing the first two array elements. l t We W assume that th t we want t the th array in i increasing i i order. If the elements are in order (that is, the first element is less than or equal to the second), second) leave them alone. alone If the elements are not in order (that is, the first is greater than the second) interchange them in the array. second), array Then, Then compare the second and third array elements. Again, if they are out of order, interchange them; otherwise, leave them alone. Continue this process until you compare the last pair of array elements. This completes p the first p pass over the array. y

To illustrate, suppose we start with the following array of five integers. 7 3 4 8 6 The first pass does the following. Because 7 and 3 are not in order, d interchange i t h them. th 3 7 4 8 6 C Compare 7 and d 4. 4 They Th are not ti in order, d so i interchange t h th them. 3 4 7 8 6 Compare 7 and 8. 8 They are in order order, so leave them and go on to the next pair. p 8 and 6. They y are not in order, , so interchange g them. Compare 3 4 7 6 8 This completes p the first p pass. The first p pass moves the largest g number in the array into the right-most position, which is where we want it when the array is completely sorted. This is why we call this sort the bubble sort. sort The largest array element "bubbles" up to the top of the array.

Now we make a second pass over the array. This time, however, we do not have to go to the end of the array because the first pass moved the largest array element into the rightmost p position. The second p pass moves the second largest g array element into the next-to-last position. Following is a trace of pass two. Start with: Begin: 3 3 3 3 4 4 4 4 7 7 7 6 6 6 6 7 8 8 8 8 Leave 3 and 4 alone Leave 4 and 7 alone I t h Interchange 7 and d6

Likewise for pass three and pass four.

Trace of Pass Three: Start with: Begin: 3 3 3 4 4 4 6 6 6 7 7 7 8 8 8 Leave 3 and 4 alone Leave 4 and 6 alone

End of Pass Three. Trace of Pass Four: Start with: Begin: 3 3 4 4 6 6 7 7 8 8 Leave 3 and 4 alone

End of Pass Four Four. The array is sorted. sorted After the fourth pass, the array is sorted.
Note that the array is sorted at the end of pass two, but the procedure keeps going. It would be more efficient if the procedure recognizes at some point that the array is sorted and ends.

An important part of the bubble sort is interchanging two array elements. To interchange the values of two variables requires the use of a third variable. For example, consider the following g declarations.
int x = 5, y = 7, , temp;

The following assignments interchange the values of x and y.


temp = x; // Places 5 into temp x = y; // Places 7 into x, destroying its contents y = temp; // Places 5 into y

#include <iostream.h> #include <time.h> // nessesary for time() int main() { const int SIZE = 10; int numbers[SIZE]; int pass, pass i i, temp; srand(time(0)); // to generate different numbers cout << "Befor sorting\n"; cout << "-------------\n"; for (i = 0; i < SIZE; i++) { numbers[i] = rand() % 100; // random numbers 0..99 cout << numbers[i] << " "; } cout << "\n\nDuring \ \ g sorting\n"; g\ ; cout << "--------------\n";

for (pass = 1; pass < SIZE; pass++) { f for (i = 0; 0 i < SIZE - pass; i++) i ) { if (numbers[i] > numbers[i+1]) { temp = numbers[i]; numbers[i] = numbers[i+1]; numbers[i+1] = temp; } } // show numbers after each p pass for (i = 0; i < SIZE; i++) cout << numbers[i] << " "; cout << endl; } cout << "\n\nAfter sorting\n"; cout << "-------------\n"; f for (i = 0; 0 i < SIZE; SIZE i++) cout << numbers[i] << " "; cout << endl; return 0; }

Sample output
Befor B f sorting ti ------------25 82 74 56 During sorting -------------25 74 56 66 25 56 66 74 25 56 66 28 25 56 28 66 25 28 56 37 25 28 37 10 25 28 10 37 25 10 28 37 10 25 28 37 After sorting ------------10 25 28 37 66 86 28 67 37 10

82 28 67 37 10 56 56 56 56

28 67 37 10 66 66 66 66 66

67 37 10 67 67 67 67 67 67

37 10 74 74 74 74 74 74 74

10 82 82 82 82 82 82 82 82

86 86 86 86 86 86 86 86 86

56

66

67

74

82

86

Initializing One-dimensional Arrays


You can fill an array with Y ith d data t a couple l of f ways. First, Fi t you can initialize the array at the same time that you declare it. You do this with an initializer list, list which is a list of values used to fill the array. Here are some examples:
float floatArray[3] = {0 {0.25, 25 .876, 876 3.0}; 3 0}; char charArray[5] = {'H','e','l','l','o'};

If you dont d include i l d the h number b of f elements l that h an array will have but include an initializer list, the array will default to the number of elements in the initializer list. list In the following line of code, charArray2 will automatically assume that the array size is 6:
char charArray2[] = {'d','r','a','g','o','n'};

If you do not have as many values in the initializer list as the y size, , the rest of the values are assumed to be 0. For array example, typing
int myArray[5] y y[ ] = { {1,2,3}; , , };

is the same as typing


int myArray[5] = {1,2,3,0,0}; {1 2 3 0 0}

Thus, its easy to initialize all the elements of an array to zero. J t explicitly Just li itl i initialize iti li th the fi first t element l t to t zero and d then th let l t the compiler initialize the remaining elements to zero:
int totals[500] = {0}; {0}

You can use the initialization form only when defining the array You cannot use it later: array. int cards[4] = {3, 6, 8, 10}; // okay int hand[4]; // okay hand[4] = {5, 6, 7, 9}; // not allowed

In C++, you cannot assign one array to another. For example the following assignment is illegal: example,
int a[5] = {1,2,3,4,5}; int b[5]; b = a; // error -- illegal

To transfer T t f th the contents t t of f one array i into t another, th you must t assign each value individually:
for (int i=0; i<5; i++) b[i] = a[i];

C-Strings
Two kinds of strings are used in C++: C-strings, C strings and strings that are objects of the string class. Well describe the first kind, in that C-strings are arrays of type char. We call these strings C-strings, or C-style strings, because they were the only kind of strings available in the C language. You can declare and initialize a C-style string the same as you would any other array. For example:
char h Greeting[] i [] = {'H','e','l','l','o','\0' { l l \0 }; }

In this case, Greeting is declared as an array of characters and it is initialized with a number of characters. characters Note the use of single quotes to delineate each character. The last character, , '\0' \ (backslash followed by ( y zero), ), is the null character, which is the terminator for a C-style string. Without it, this array would simply represent an array of characters, h t not t a string. t i Not N t providing idi a terminating t i ti null ll character for a string can cause logic errors.

Although this character-by-character approach works, it is difficult to type and admits too many opportunities for error. C++ enables you to use a shorthand form of the previous line of code. It is char Greeting[] = "Hello"; The size of array Greeting in the preceding declaration is d t determined i d by b the th compiler il based b d on the th length l th of f the th string. t i It is important to note that the string "Hello" contains five characters plus a special string string-termination termination character called the null character. Thus, array Greeting actually contains six elements. You should note two things about this syntax: Instead of single-quoted characters separated by commas and surrounded by braces, you have a double-quoted Cstyle string, no commas, and no braces. You Y dont d t need d to t add dd the th null ll character h t b because th the compiler adds it for you.

Because a string is an array of characters, we can access individual characters in a string directly with array subscript notation. For example, Greeting[0] is the character 'H', Greeting[3] g is the character 'l' and Greeting[5] g is the null character. p a string g directly y into a character array y We also can input from the keyboard using cin and >>. For example, the declaration
char name[20];

creates a character array y capable p of storing g a string g of 19 characters and a terminating null character. The statement
cin >> name;

reads a string from the keyboard into name and appends the g input p by y the user. null character to the end of the string

A character array representing a null-terminated string can p with cout and <<. The statement be output
cout << name;

prints i t the th array name. Note N t that th t cout <<, like lik cin >>, does d not t care how large the character array is. The characters of the string are output until a terminating null character is encountered.

Note:
cin and cout assume that character arrays should be processed as strings terminated by null characters; cin and cout do not provide similar input and output processing capabilities biliti for f other th array types. t

Sample program
#include <iostream.h> <iostream h> int main() { const int SIZE = 20; char name[SIZE]; cout << "Enter your name: "; cin >> name; cout << "Your name is " << name << ".\n"; return 0; }

Output
Enter your name: Omar Your name is Omar.

Avoiding Buffer Overflow


The previous program invites the user to type in a string. string What happens if the user enters a string that is longer than y used to hold it? As we mentioned earlier, , there is no the array built-in mechanism in C++ to keep a program from inserting array elements outside an array. So an overly enthusiastic typist could end up crashing the system. However, it is possible to tell the >> operator to limit the number b of f characters h t it places l in i an array. The Th next t program demonstrates this approach. It uses the setw manipulator to specify the maximum number of characters the input buffer can accept. The user may type more characters, but the >> operator wont insert them into the array. Actually, one character fewer than the number specified is inserted, so there is room in the buffer for the terminating null character. Th Thus, i in thi this example, l a maximum i of f 19 characters h t are inserted.

Example: avoiding buffer overflow with cin.setw


#include <iostream.h> <iostream h> #include <iomanip.h> int main() { const int SIZE = 10; char name[SIZE]; cout t << "E "Enter t your name: " "; cin >> setw(SIZE) >> name; cout << "Your name is " << str << ".\n"; return 0; }

Output Enter your name: OmarKatayah Your name is OmarKatay.

Reading Embedded Blanks


If you t tried i d t to i input t strings t i th that t contained t i d more than th one word, you may have had an unpleasant surprise. Heres an example:
Enter your name: Omar Katayah Yo r name is Omar Your Omar.

Where did the rest of the name g go? It turns out that the extraction operator >> considers a space to be a terminating character. Thus it will read strings consisting of a single word, but anything typed after a space is thrown away. To read text containing g blanks we use another function, , cin.get(). The following example shows how its used:

#include <iostream> int main() { const int SIZE = 20; char name[SIZE]; cout << "Enter your name: "; cin.get(name, SIZE); cout << "Your name is i " << name << ".\n"; \ return 0; }

The first argument to cin.get() is the array variable where the string being input will be placed. placed The second argument specifies the maximum size of the array, thus automatically g buffer overrun. Using g this function, , the input p string g avoiding is now stored in its entirety.
Enter te your you name: a e: Omar O a Katayah ataya Your name is Omar Katayah.

Mixing String and Numeric Input


Mixing numeric input with line-oriented line oriented string input can cause problems. Consider the following simple program:
#include <iostream.h> <iostream h> int main() { cout << "What year was your house built? \n"; int year; cin >> year; cout << "What is its street address? \n"; char address[80]; cin.getline(address, 80); cout << "Year built: " << year << "\n"; cout << "Address: Address: " << address << "\n"; \n ; cout << "Done!\n"; return 0; }

Running this program would look something like this:


What Wh t year was your house h built? b ilt? 1966 What is its street address? Year built: 1966 Address Done!

You never get the Y h opportunity i to enter the h address dd . The Th problem is that when cin reads the year, it leaves the newline generated by the <Enter> key in the input queue. queue Then Then, cin.getline() reads the newline as an empty line and g a null string g to the address array. y The fix is to read assigns and discard the newline before reading the address. This can be done several ways, including using get() with no argument or with a char argument, as described in the preceding example.

You can make this call separately:


cin >> year; cin.get(); // or cin.get(ch);

Or, you can concatenate O t t the th call, ll making ki use of f the th f fact t th that t the expression cin >> year returns the cin object:
( i >> year).get(); (cin ) () // or (cin ( i >> year).get(ch); ) ( h)

If you make one of these changes, it works properly:


What year was your house built? 1966 What is its street address? 43821 Year built: b il 1966 Address: 43821 Done!

Converting Strings to Numbers


You can also Y l use a couple l of ff functions ti t to convert t strings t i th that t contain numeric values to the numeric value (for example, 5 to 5). ) "5" To convert a string representation of an integer to an integer, use the atoi() function. To use this function, you pass in a string, and the function returns an integer. Here is an example: char s[] = "567"; int x = atoi(s) + 3; cout << x; This code displays the number 570 onscreen.

You can also use functions to convert a string to a double and a string to a long; they are, atof() and atol(), respectively. These functions also work the exact same way as atoi() () does. If the string does not contain a number (for example, "HI"), 0 is returned.
These functions can be useful for receiving user input. Instead of assuming that users will enter valid numbers, you can let them enter a string. Then you can check to see whether this string can be converted to a number. This is a much safer way to receive user input.

Sample Program: Circumference and area of a circle


#include <iostream.h> const double pi = 3.141593; int main() { double circuit, area, radius; char str_radius[10]; do { cout << "Radius = "; cin i >> str_radius; t di // safer f i input t radius = atof(str_radius); } while (radius == 0); circuit = 2 * pi * radius; area = pi * radius * radius; cout << "\nRadius: " << radius << "\nCircumference: " << circuit << "\nArea: " << area << endl; return 0; }

Sample output
Radius di = abc b Radius = xy12 Radius = 1.5 Radius: 1.5 Circumference: 9.42478 9 42478 Area: 7.06858

Multidimensional Arrays
Arrays that A th t we have h seen so f far h have been b unidimensional. idi i l We can talk of the length of the array in a sense similar to the length of a line, line and array elements can be located by a single subscript parameter the same way that points on a line can be y their distance from the beginning. g g identified by Arrays can, however, get multidimensional too. For example, points in a rectangular area can be represented by a multidimensional one. This array-based representation of points in a rectangular area would need two subscript parameters, x and y (two dimensions), which are necessary to locate a point within an area. Arrays programmed in C++ exist in a virtual world and are not limited by two dimensions alone. You can create an array of any number of dimensions, and that is what makes multidimensional arrays an interesting topic from mathematical points of view.

Declaring Multidimensional Arrays


Each E h dimension di i i in an array i is represented d as a subscript b i i in the array. Therefore, a two-dimensional array has two subscripts; b i t a three-dimensional th di i l array h has th three subscripts; b i t and so on. Arrays can have any number of dimensions. The most Th t common multidimensional ltidi i l array t type i is th the t twodimensional array, the so-called matrix. The general form for declaring a two-dimensional array is:

type arrayName[rows][columns];
A good example of a two-dimensional array is a chess board. One dimension represents p the eight g rows; ; the other dimension represents the eight columns.

The declaration of an array that would represent the board, as q would be a collection of squares int board[8][8];

Using Tow-dimensional Arrays


E Example: l
float number[3][10]; // 3 x 10 matrix

This defines a matrix called number that contains 3 rows and 10 columns. Each of the 30 (3 x 10) elements is a float type. The assignment
number[0][9] = 7.2; // Row 0, column 9

stores the value 7.2 in the last element of the first row. You can also input values from the keyboard:
cin >> number[0][9];

Example: Matrices Addition


#include <iostream.h> <iostream h> int main() { const int n = 3; double A[n][n], B[n][n], C[n][n]; int i, j; cout << "Enter the values of matrix A:\n"; for (i=0; i<n; i++) for (j=0; j<n; j++) { cout << "A[" << i << "][" << j << "]="; cin >> A[i][j]; } cout << "\nEnter the values of matrix B:\n"; for (i=0; i<n; i++) f for (j 0 j<n; (j=0; j< j++) { cout << "B[" << i << "][" << j << "]="; cin >> B[i][j]; }

// addition for (i=0; i<n; i++) for (j=0; j<n; j++) C[i][j] = A[i][j] + B[i][j]; cout << "\nC=A+B=\t"; // output for (i=0; i<n; i++) { for (j=0; j<n; j++) cout << C[i][j] << " cout << endl; cout << "\t"; \t ; } cout << endl; return 0; }

";

Sample Output
Enter the valus of Matrix A: A[0][0]=0 A[0][1]=-1 A[0][2]=2 [ ][ ] A[1][0]=4 A[1][1]=2 A[1][2]=1 A[2][0]=1 A[2][1]= 2 A[2][1]=-2 A[2][2]=5 Enter the valus of Matrix B: B[0][0]=1 B[0][1]=0 B[0][2]=-1 B[1][0]=2 B[1][1]=-4 B[1][2]=3 B[2][0]=1 [ ][ ] B[2][1]=5 B[2][2]=0 C=A+B= 1 6 2 -1 1 -2 2 4 3 5

Example: Matrices Multiplication

C[0][0] = A[0][0]*B[0][0] + A[0][1]*B[1][0] + A[0][2]*B[2][0]; C[0][1] = A[0][0]*B[0][1] A[0][0] B[0][1] + A[0][1]*B[1][1] A[0][1] B[1][1] + A[0][2]*B[2][1]; A[0][2] B[2][1]; C[0][2] = A[0][0]*B[0][2] + A[0][1]*B[1][2] + A[0][2]*B[2][2]; C[1][0] = A[1][0]*B[0][0] + A[1][1]*B[1][0] + A[1][2]*B[2][0]; C[1][1] = A[1][0]*B[0][1] + A[1][1]*B[1][1] + A[1][2]*B[2][1]; C[1][2] = A[1][0]*B[0][2] + A[1][1]*B[1][2] + A[1][2]*B[2][2]; C[2][0] = A[2][0]*B[0][0] + A[2][1]*B[1][0] + A[2][2]*B[2][0]; C[2][1] = A[2][0]*B[0][1] + A[2][1]*B[1][1] + A[2][2]*B[2][1]; C[2][2] = A[2][0]*B[0][2] + A[2][1]*B[1][2] + A[2][2]*B[2][2]; for (i=0; i<n; i++) for (j=0; j<n; j++) C[i][j] = A[i][0]*B[0][j] + A[i][1]*B[1][j] + A[i][2]*B[2][j]; A[i][2]*B[2][j] for (i=0; i<n; i++) for (j=0; j<n; j++) for (k=0; k<n; k++) C[i][j] [ ][j] += A[i][k] [ ][ ] * B[k][j]; [ ][j];

#include <iostream.h> int main() { const int n = 3; ; int i, j, k; double A[n][n], B[n][n], C[n][n] = {0}; // initializing A[0][0] = 0; A[0][1] = -1; A[0][2] = 2; A[1][0] = 4; A[1][1] = 2; A[1][2] = 1; A[2][0] = 1; A[2][1] = -2; A[2][2] = 5; B[0][0] = 1; B[0][1] = 0; B[0][2] = -1; B[1][0] = 2; B[1][1] = -4; B[1][2] = 3; B[2][0] = 1; B[2][1] = 5; B[2][2] = 0;

// multiplication for ( (i=0; i<n; i++) ) for (j=0; j<n; j++) for (k=0; k<n; k++) C[i][j] + += A[i][k] * B[k][j]; // output cout << "A="; A= ; for (i=0; i<n; i++) { cout t << "\t" "\t"; for (j=0; j<n; j++) cout << A[i][j] << " "; cout << "\n"; \ } cout << "------------------\n"; }

cout << "B="; for (i=0; i<n; i++) { cout << "\t"; for (j=0; j<n; j++) cout << B[i][j] << " "; cout << "\n"; } cout << "------------------\n"; cout << "C=A*B="; C A B ; for (i=0; i<n; i++) { cout << "\t"; \t ; for (j=0; j<n; j++) cout << C[i][j] << " "; cout t << "\ "\n"; " } cout << "------------------\n"; }

Output
A= 0 -1 2 4 2 1 1 -2 5 -----------------B= 1 0 -1 2 -4 3 1 5 0 -----------------C=A*B= 0 14 -3 3 9 -3 2 2 33 -7 ------------------

Initializing Multidimensional Arrays


To initialize multidimensional arrays you assign the list of values to array elements in order, with the last array subscript (the one farthest to the right) ( g ) changing g g while each of the former holds steady. Therefore, if you have an array
int myArray[4][3]; y y[ ][ ]

You initialize this array by writing


int myArray[4][3] = {1,2,3,4,5,6,7,8,9,10,11,12}; {1 2 3 4 5 6 7 8 9 10 11 12};

the first three elements go into myArray[0]; the next three into myArray[1]; and so forth. forth For the sake of clarity, you could group the initializations with braces. For example: int myArray[4][3] = {{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}};

The compiler ignores the inner braces, but they do make it easier to understand how the numbers are distributed. When initializing elements of an array, each value must be separated by a comma, without regard to the braces. The entire initialization set must be within braces, and it must end with a semicolon.

Pointers
Addresses Add and dP Pointers i t The Address-of Operator (&) Using Pointers The Indirection Operator (*) Distinguishing Between a Pointer and the Pointed-to Value Using an Unassigned Pointer Null Pointers Pointers and Arrays Names of Arrays are Constant Pointers Dynamic Memory Allocation Creating Dynamic Arrays Arrays of Pointers

Addresses and Pointers


Every byte E b t in i the th computers t memory has h an address dd . Addresses are numbers, just as they are for houses. The program when it is loaded into memory, program, memory occupies a certain range of these addresses. That means that every variable y function in the p program g starts at a p particular and every address. A pointer is a variable that holds a memory address. The memory address that the pointer stores is the address of another variable. So a pointer is said to point to a variable. The syntax for declaring a pointer is as follows:

data_type * pointer_name;
Here, data_type Here data type is the type of the variable being pointed to, to and pointer_name is the name of the pointer.

The Address-of Operator (&)


First, you must learn about a new operator, First operator the address-of address of operator (&). You put it directly in front of a variable, and it evaluates to the memory address of the variable.
#include <iostream.h> int main() { int v1 = 11; int v2 = 22; cout << "The address of v1 is: " << &v1 << endl << "The address of v2 is: " << &v2 << endl; return 0; }

Output The address of v1 is: 0012FED4 The address of v2 is: 0012FEC8

Using Pointers
The address-of address of operator (&) is useful for assigning values to a pointer. Here is an example of how to use the address-of operator with pointers:
int x; p int *p p = &x;

or:
int x; p = &x; int *p

This code makes p points to x.

#include <iostream.h> int main() { int v1 = 11; int v2 = 22; cout << "The address << "The address int *ptr; p ; ptr = &v1; cout << "The address ptr = &v2; cout << "The address return 0; }

of v1 is: " << &v1 << endl of v2 is: " << &v2 << endl;

of v1 is: " << ptr << endl; of v2 is: " << ptr << endl;

Output Th address The dd The address The address The address

of f of of of

v1 1 v2 v1 v2

is: i is: is: is:

0012FED4 0012FEC8 0012FED4 0012FEC8

The Indirection Operator (*)


The indirection operator (*) is used to refer to the object pointed to by the pointer. You place the indirection operator right in front of a pointer and it evaluates to the value of the variable that the pointer points to. This operator is different from the (*) used to declare a pointer. For example, if you declare an integer and a pointer as int x = 78; int *p = &x; y can use the indirection operator you p to access the value of x through p like this:
cout << "The value of x is: " << *p; p

This code displays the number 78 onscreen. You can think of the indirection operator (sometimes called the dereferencing operator) as the opposite of the addres-of operator.

#include <iostream.h> int main() { int v1 = 11; int v2 = 22; int *ptr; ptr t = & &v1; 1 cout << "v1 = " << *ptr << endl; ptr = &v2; cout << "v2 = " << *ptr << endl; return 0; }

O t t Output
11 22

Distinguishing Between a Pointer and the Pointed-to Value


Remember, if pt is a pointer-to-int, Remember pointer-to-int *pt is not a pointer-toint; instead, *pt is the complete equivalent to a type int variable. It is pt that is the pointer. Here is an example: int x, *pt = &x; x = 5; cout << "The value of x cout << "The address of *pt = 8; cout << "The value of x cout << "The The address of

is: " << *pt << "\n"; x is: " << p pt << "\n\n"; \ \ ; is: " << x << "\n"; x is: " << pt << "\n"; \n ;

Output
The value of x is: 5 The address of x is: 0012FF60 The value of x is: 8 The address of x is: 0012FF60

Using an Unassigned Pointer


The following program declares a pointer and then attempts to output its value without first assigning it a value:
// An incorrect program. Do Not Execute! #include <iostream.h> int main() { int *ptr; cout t << "Th "The value l of f ptr t i is " << ptr t << endl; dl return 0; }

The result, depending on your compiler and operating system, t may be b a compiler il error, a runtime ti error, or a computer that locks up. Regardless, attempting to use a declared pointer without first assigning it a value is not a good idea.

Null Pointers
If it is too early in your code to know which address to assign to the pointer, then you first assign the pointer NULL, which is a constant with a value of zero defined in several standard libraries, including iostream.h. The following program does so: #include <iostream.h> int main() { int *ptr = NULL; cout << "The value of ptr is " << ptr << endl; return 0; } The resulting output is: "The value of ptr is 00000000 A pointer i t that th t is i assigned i d NULL is i called ll d a null ll pointer. i t

Pointers and Arrays


Arrays and pointers are closely linked. linked In fact, fact names of arrays are pointers. Consider this array:
double f[10];

The name of the array, f, acts as a pointer to the first element. The following code displays the value of the first element:
cout << *f;

If you declare a pointer to the same type as the arrays type, type you can assign the pointer to the first element of the array like this:
double *pf = f;

This code snippet is synonymous to the following one:


double *pf = &f[0];

Then you can go through every element in the array by incrementing the pointer. pointer You increment a pointer just like you do any other variable. Because a pointer stores a memory , incrementing gap pointer changes g the memory y address. address, Instead of going up by one, however, the value of the memory address is increased by the size of the pointer type. This effectively moves on to the next element in the array, as shown in this example:
double f[] = {5.5, 0.5 , 6.7}; double *pf = f; cout << *pf; pf; cout << " " << *(++pf); cout << " " << *(++pf);

This code displays 5.5 0.5 6.7 on the screen. Every time you increment a pointer, it moves on to the next element of the array.

Look at this example:


# c ude <iostream.h> #include ost ea . int main() { int intArray[5] = {31 {31, 54, 54 77, 77 52, 52 93}; for (int j=0; j<5; j++) cout << intArray[j] << endl; return 0; }

and this example:


#include <iostream.h> int main() { int intArray[5] = {31, 54, 77, 52, 93}; for (int j=0; j<5; j++) cout << *(intArray+j) << endl; return 0; }

The expression *(intArray+j) has exactly the same effect as intArray[j], and the outputs of the two programs are identical. The C++ compiler knows that intArray is an array of type int because it was declared that way. way So when j is 3 for example, and the compiler sees the expression intArray+3, it interprets it as the address of the fourth integer in intArray. But we want the value of this fourth array element, element not the address. address To take the value, value we use the indirection operator (*). The resulting expression, when j is 3, is *(intArray+3), which is the content of the fourth array element, or 52.

Names of Arrays are Constant Pointers


While the Whil th pointer i t may be b a variable, i bl it also l may b be a constant, but the name of an array is a constant pointer. You cannot t change h the th value l of f the th name of f the th array. For F example, a statement such as intArray++ would result in a compiler error, error the error message being '++'needslvalue The term l-value refers to the value to the left of the assignment operator. This error message is another way of saying you cant increment a constant because that would be changing the value of a constant after you declare it.

Dynamic Memory Allocation


We saw that W th t when h declaring d l i an array, the th size i of f the th array must be either a literal or a constant, and may not be a variable It is often desirable to have the user determine at variable. runtime the size of the array so it is neither too small nor too large but just right. large, right To accomplish this, this you need to declare the array using dynamic memory allocation. With d dynamic i memory allocation, ll ti memory i is not t b being i allocated at compile time. Instead, memory is being allocated at t runtime, r time and d from a different differe t place pl ce (the he heap) p) r rather ther than where it is allocated at compile time (the stack).

You allocate memory on the heap using the new operator. This operator returns a pointer to the newly allocated memory. To use this memory, you must assign it to a pointer variable. The syntax y for the new operator p is as follows:

pointer = new data_type;


Here data_type is H i any valid lid data d t t type. F For example, l to t create t an integer on the heap, you do the following:
int *a = new int;

To create a double on the heap, you do the following:


double *x = new double;

All memory that you allocate with the new operator must be deallocated with the delete operator. If you do not free the memory you use, this memory will not be available to use later in the p program. g Forgetting g g to free dynamic y memory y is called a memory leak, and you should always avoid it. The syntax for the delete operator is as follows:
delete pointer;

For example, F l to free f the h memory allocated ll di in the h preceding di examples, do the following: d l delete a; delete x;

Creating Dynamic Arrays


The syntax for creating an array dynamically on the heap is: pointer = new data_type[arraySize]; You can use a variable expression for the number of elements in the array, as shown here: int x; cin >> x; double *d = new double[x]; To deallocate the memory for the preceding array, you use the delete[] operator. d l t [] pointer delete[] i t ; To free the memory allocated in the preceding example, do the following: delete[] d; The delete[] operator frees the entire array, array so you don dont t have to worry about each element.

The following program uses dynamic memory allocation:


#include #incl de <iostream.h> <iostream h> int main() { i t numTests, int T t i i; cout << "Enter the number of test scores: "; cin >> numTests; i t *ptr int * t = new int[numTests]; i t[ t ] for (i=0; i<numTests; i++) { cout << "Enter test score #" # << i + 1 << ": "; cin >> ptr[i]; } cout << endl; for (i=0; i<numTests; i++) cout << "Test score #" << i + 1 << " is " << ptr[i] << endl; delete[] ptr; return 0; }

Some sample input and output:


Enter Enter Enter Enter Enter Test Test Test Test the number test score test score test score test score score score score score #1 #2 #3 #4 is is is is of test scores: 4 #1: 66 #2: 88 #3: 77 #4: 50 66 88 77 50

Arrays of Pointers
Arrays may contain pointers. pointers A common use of such a data structure is to form an array of pointer-based strings, referred to as a string array. Each entry in the array is a string, but in C++ a string is essentially a pointer to its first character, so each entry in an array of strings is simply a pointer to the first character of a string. Consider the declaration of string array suit that might be useful in representing i ad deck k of f cards: d
const char *suit[4] = {"Hearts", "Diamonds", "Clubs", "Spades"};

The suit[4] portion of the declaration indicates an array of four elements. The const char * portion of the declaration indicates that each element of array suit is of type "pointer t char to h constant t t d data." t " Th The four f values l to t be b placed l d in i the th array are "Hearts", "Diamonds", "Clubs" and "Spades".

Each is stored in memory as a null-terminated character g that is one character longer g than the number of string characters between quotes. The four strings are seven, nine, six and seven characters long (including their terminating null characters), respectively. Although it appears as though these strings are being placed in the suit array, only pointers are actually t ll stored t d in i the th array. E Each h pointer i t points i t to t the th first character of its corresponding string. Thus, even though the suit array is fixed in size size, it provides access to character strings of any length. This flexibility is one example of C++'s powerful data-structuring p g capabilities. p

Functions
What Is a Function? Using Functions Declaring the Function Defining the Function Eleminating the Declaration Return Values Passing Constant Arguments to Functions ss g Variables s to Functions s Passing Determining Variable Scope Local Variables Global Variables L Local lV Variables i bl Within Wi hi Blocks Bl k Parameters Are Local Variables Using Functions as Parameters to Functions Parameters with Default Values Passing Arguments by References Using Pointers as arguments to Functions Passing Arrays to Functions Overloading Functions Recursion

What Is a Function?
A function f ti is, i in i effect, ff t a subprogram b that th t can act t on data d t and return a value. Every C++ program has at least one function main(). When the program starts, function, starts the function main() is called automatically. main() might call other functions some of which might call others. functions, others Each function has its own name, and when that name is encountered the execution of the program branches to the encountered, body of that function. When the function returns, execution resumes on the next line of the calling function. function Functions come in two varieties: user-defined and built-in. Built in functions are part of the compiler package. Built-in package They are supplied by the manufacturer for programmers use. Mathematical functions are examples of built-in functions. functions

Using Functions
T use a C++ f To function, ti you must t do d the th following: f ll i Provide a function declaration (prototype). Provide a function definition. definition Call the function.

If youre you re using a library function, function the function has already been defined and compiled for you. You use the library header file to provide the prototype. All that thats s left to do is call the function properly. For example, the math library includes the sqrt() function for finding the square root of a number. The associated standard header file math.h contains the function prototype for sqrt() and several other mathematical f functions. i But when you create your own functions, you have to handle all ll three th aspects: t declaring, d l i defining, d fi i and d calling lli the th function f ti yourself.

Declaring the Function


A function f ti declaration d l ti tells t ll the th compiler il that th t a function f ti exists. You tell the compiler the name of the function, what the parameters are, are and what the function returns. returns Here is the general syntax for a function declaration:
return type function return_type function_name name([type [parameterName]] [parameterName]]...);

Examples:
void StarsLine(); void Stars(char c, int n); int GetChoice(); float FindArea(float length, float width); double Average(int A, int B, int C); int Round(double x);

A function declaration is also called a prototype because it is a model of the function. A function prototype is a statement, so it must have a terminating semicolon. However, the function prototype does not require that you provide names for the variables; a list of types is enough. In general, you can either include or exclude variable names in the argument lists for prototypes. The variable names in the prototype just act as placeholders, so if you do use names, th they dont d t have h to t match t h the th names in i the th function f ti definition.
float FindArea(float, fl i d (fl fl float); ) double Average(int, int, int);

Defining the Function


The d Th definition fi iti of f a function f ti consists i t of f the th function f ti header h d and its body. The header is exactly like the function prototype except that the parameters must be named, prototype, named and there is no terminating semicolon. The b Th body d of f th the function f ti is i a set t of f statements t t t enclosed l d in i braces.

returnType functionName([type [parameterName]]..)


{

statement; statement;
... return; ; }

Function Definition Examples:


double Area(double l, double w) { return (l * w); } void PrintMessage(int whichMsg) { if (whichMsg == 0) cout << "Hello.\n"; if (whichMsg == 1) cout << "Goodbye.\n"; \ if (whichMsg > 1) cout << "I'm I m confused.\n"; confused.\n ; }

Sample program
#include <iostream.h> void StarsLine(); // function declaration int main() { StarsLine(); cout << "Data type \tRange\n"; StarsLine(); (); cout << "short \t\t-32,768 to 32,767\n"; cout << "int \t\tSystem dependent\n"; cout << "long long \t\t \t\t-2 2,147,483,648 147 483 648 to 2,147,483,647\n 2 147 483 647\n"; ; StarsLine(); return 0; } void StarsLine() // function definition { f for (i (int j 0 j<50; j=0; j 50 j++) j ) cout << '*'; cout << endl; }

Output
************************************************** Data type Range ************************************************** short -32,768 to 32,767 y dependent p int System long -2,147,483,648 to 2,147,483,647 **************************************************

Eliminating the Declaration


#include #i l d <iostream.h> <i t h> void StarsLine() // function definition { for (int j=0; j<50; j++) cout << '*'; cout << endl; } int main() { StarsLine(); cout << "Data type \tRange\n"; StarsLine(); cout << "short \t-32,768 to 32,767\n"; cout << "int \tSystem dependent\n"; co t << "long \t-2,147,483,648 cout \t 2 147 483 648 to 2,147,483,647\n"; 2 147 483 647\n" StarsLine(); return 0; }

Return Values
To return T t a value l f from a f function, ti write it the th keyword k d return t followed by the value you want to return. The value might itself be an expression that returns a value. value For example: return; // used in void functions return 5; return (x * y); return (MyFunction()); return (x > 5); // returns true or false These are all Th ll l legal l return t statements, t t t assuming i th that t th the function MyFunction() itself returns a value. The value in the fifth statement, statement return ret rn (x ( > 5), will be false if x is not greater than 5 or it will be true. What is returned is the value of the expression, expression false or true, not the value of x. x

When the return keyword is encountered, the expression following return is returned as the value of the function. Program execution returns immediately to the calling function, and any statements following return are not executed. t d It is legal to have more than one return statement in a single function. function

Passing Constant Arguments to Functions


#include <iostream.h> <iostream h> void RepChar(char, int); int main() { RepChar('-', 47); cout << "Data type \tRange\n"; RepChar('=' RepChar( = , 21); cout << "short \t\t-32,768 to 32,767\n"; cout << "int \t\tSystem dependent\n"; cout << "long long \t\t \t\t-2 2,147,483,648 147 483 648 to 2,147,483,647\n 2 147 483 647\n"; ; RepChar('-', 47); return 0; } void RepChar(char ch, int n) { for (int j j=0; 0; j<n; j++) cout << ch; cout << endl; }

Output ----------------------------------------------Data type Range ===================== short -32,768 to 32,767 int System dependent long -2,147,483,648 to 2,147,483,647 -----------------------------------------------

Passing Variables to Functions


#include #i l d <iostream.h> <i t h> double FindArea(double length, double width); int main() { double lengthOfYard, widthOfYard, area; cout << "\nHow wide is y your y yard in meter? "; cin >> widthOfYard; cout << "\nHow long is your yard in meter? "; cin >> lengthOfYard; area = FindArea(lengthOfYard, widthOfYard); cout << "\nYour yard is " << area; cout << " square meter meter.\n\n \n\n"; ; return 0; } do ble FindArea(double double FindArea(do ble l, l double do ble w) ) { return (l * w); }

Output How wide is your yard? 100 How long is your yard? 200 Your yard is 20000 square meter.

Determining Variable Scope


A variable i bl has h scope, which hi h d determines t i h how l long it is i available to your program and where it can be accessed. V i bl declared Variables d l d within ithi a block bl k are scoped d to t th that t block; bl k they can be accessed only within that blocks braces and go out of existence e istence when hen that block ends. ends Global variables ariables have ha e global scope and are available anywhere within your program. program

Local Variables
Not N t only l can you pass i in variables i bl t to th the f function, ti but b t you can also declare variables within the body of the function. V i bl you d Variables declare l within ithi the th b body d of f th the function f ti are called local because they only exist locally, within the function itself. itself When the function returns, returns the local variables ariables are no longer available; they are marked for destruction by the compiler. compiler Local variables are defined the same as any other variables. Th parameters The t passed di in to t the th function f ti are also l considered id d local variables and can be used exactly as if they had been d fi d within defined ithi the th body b d of f the th function. f ti

Sample program
#include <iostream.h> <iostream h> float Convert(float); int main() { float TempFer, TempCel; // local variables cout << "Enter the temperature in Fahrenheit: "; cin >> TempFer; TempCel = Convert(TempFer); cout << "\nThe temperature in Celsius is: "; cout << TempCel << endl; return 0; } float Convert(float TempFer) { float TempCel; // local variable TempCel = ((TempFer - 32) * 5) / 9; return TempCel; }

Output Enter the temperature in Fahrenheit: 212 The temperature in Celsius is: 100
Enter the temperature in Fahrenheit: 32 The temperature in Celsius is: 0 Enter the temperature in Fahrenheit: 85 The temperature in Celsius is: 29.4444

Global Variables
#include #i l d <iostream.h> <i t h> void myFunction(); int x = 5, y = 7; // global variables int main() { cout << "We are in main\n"; cout << "x = " << x << " ", y = " << y << myFunction(); cout << "We are in main again!\n"; cout << "x x = " << x << ", y = " << y << return 0; } void myFunction() { int y = 10; // local variable cout << "We We are in myFunction\n"; myFunction\n ; cout << "x = " << x << ", y = " << y << cout << "modifying x in myFunction: x = cout << "\n\n"; \n\n ; }

"\n\n";

"\n\n"; \n\n ;

"\n"; " << ++x;

Output We are in main x = 5, y = 7


We are in myFunction x = 5, , y = 10 modifying x in myFunction: x = 6 We are in main again! x = 6, y = 7

Local Variables Within Blocks


You can d Y define fi variables i bl anywhere h within ithi th the f function, ti not t just at its top. The scope of the variable is the block in which it is defined. defined Thus, Thus if you define a variable inside a set of braces within the function, that variable is available only within that block. block The following program illustrates this idea.

Sample program
# #include <iostream.h> void myFunc(); int main() { int x = 5; cout << "In main x = " << x; myFunc(); cout t << "\ "\nBack B k i in main, i x = " << x << endl; dl return 0; } void myFunc() { int x = 8; // local variable in the function cout << "\nIn \nIn myFunc, local x = " << x << endl; { cout << "\nIn block in myFunc, x = " << x; int x = 12; // local variable in a block cout << "\nVery local x = " << x; } cout << "\nOut of block, in myFunc, x = " << x << endl; }

Output In main x = 5 In myFunc, local x = 8


In block in myFunc, x = 8 Very y local x = 12 Out of block, in myFunc, x = 8 Back in main, x = 5

Parameters Are Local Variables


When arguments are passed Wh d by b value, l the h called ll d f function i creates a new variable of the same type as the argument and copies i th the arguments t value l into i t it. it The Th f function ti cannot t access the original variable in the calling program, only the copy it created. created Passing arguments by value is useful when the function does not t need d to t modify dif th the original i i l variable i bl i in th the calling lli program. In fact, it offers insurance that the function cannot harm the original variable. variable

Sample program
#include <iostream.h> <iostream h> void Swap(int x, int y); int main() { int x = 5, y = 10; cout << "Main. Before swap, x:" << x << " y:" << y; S Swap(x, ( y); ) cout << "Main. After swap, x:" << x << " y:" << y; return 0; { void Swap(int x, int y) { int temp; cout << "Swap. Before swap, x:" << x << " y:" << y; temp = x; x = y; y = temp; cout << "Swap. After swap, x:" << x << " y:" << y; }

Output Main. Before swap, x: 5


Swap. B S Before f swap, x: 5 Swap. After swap, x: 10 Main. After swap, x: 5

y: 10 y: 10 y: 5 y: 10

Using Functions as Parameters to Functions


Although Alth h it is i legal l lf for one f function ti to t take t k as a parameter t a second function that returns a value, it can make for code that is hard to read and hard to debug. debug As an example, say you have the functions Double(), Triple(), Square(), and Cube(), each of which returns a value. You could write
int myValue = 2, 2 answer; answer = (Double(Triple(Square(Cube(myValue)))));

This statement takes a variable, variable myValue, myValue and passes it as an argument to the function Cube(), whose return value is passed as an argument to the function Square(), whose return value is in turn passed to Triple(), and that return value is passed to Double(). The return value of this doubled, tripled, squared, and cubed number is now passed to answer.

It is difficult to be certain what this code does (was the value tripled before or after it was squared?), and if the answer is wrong it will be hard to figure out which function failed. An alternative is to assign each step to its own intermediate variable:
int int int int int myValue = 2; cubed = Cube(myValue); squared = Square(cubed); tripled = Triple(squared); answer = Double(tripled); // // // // cubed = 8 squared = 64 tripled = 192 Answer = 384

Now each N hi intermediate di result l can be b examined, i d and d the h order d of execution is explicit.

Parameters with Default Values


A function can be called without specifying all its parameters. When declaring a function, you can specify default values for one or more p parameters in the p parameter list. For example: int function1(int x = 50); int function2(int x, int y = 20); int function3(int x, x int y = 5 5, int z = 10); The function definition header for this function would be int function1(int x) int function2(int x, int y) int function3(int ( x, , int y, int z) ) This initialization syntax directs the compiler to use the default value specified p in the p prototype yp when no actual value is specified in the call in the client code.

Notice that the default values for parameters with default values should be specified in the prototype, not in the function definition. The function definition cannot contain the default value. C++ allows default values for right-most parameters only. If you define a default argument for a parameter, parameter all following parameters must have default arguments.
int foo(int a=0, a 0 int b=2, b 2 double do ble c); c) // wrong rong

Using default parameter values in some cases can simplify client code when a function with a large number of parameters is called mostly for the same values of arguments and only seldomly for other argument values.

Sample program
#include <iostream.h> int CubeVolume(int l, int w = 25, int h = 1); int main() { int length = 100; int width = 50; int height = 2; int volume; volume = CubeVolume(length, width, height); q " << volume << endl; cout << "First area equals: volume = CubeVolume(length, width); cout << "Second time area equals: " << volume << endl; ( g ) volume = CubeVolume(length); cout << "Third time area equals: " << volume << endl; return 0; } int CubeVolume(int length, int width, int height) { return (length * width * height); }

Output
First area equals: 10000 Second time area equals: 5000 Third time area equals: 2500

Passing Arguments by References


A reference f provides id an alias li a different diff t name for f a variable. When you create a reference, you initialize it with the name of another object object, the target target. From that moment on, on the reference acts as an alternative name for the target, and y gy you do to the reference is really y done to the target. g anything You create a reference by writing the type of the target object, followed by the reference operator (&), followed by the name of the reference, followed by an equal sign, followed by the name of the target object. References can have any legal variable name, but some programmers prefer to prefix reference names with the letter r. Thus, Th if you have h an i integer variable i bl named d length, you can make a reference to that variable by writing the following:

int length; int &rRef = length;

This statement is read as rRef is a reference to an integer. g . The reference is initialized to refer to length References differ from other variables in that they must be initialized when they are declared declared. If you try to create a reference variable without assigning, you receive a compiler error. The folowing example shows how references are created and used.

Sample program
# #include <iostream.h> int main() { int x; int &rx = x; x = 5; cout << "x x = " << x << endl; cout << "rx = " << rx << endl; rx = 7; cout << "x x = " << x << endl; cout << "rx = " << rx << endl; return 0; }

Output
x = 5 rx = 5 x = 7 rx = 7

One of the most important uses for references is in passing arguments to functions. functions Passing arguments by reference uses a different mechanism than passing arguments by value. value Instead of a value being passed to the function, a reference to the original variable, in g p program, g , is p passed. Its actually y the memory y the calling address of the variable that is passed. An important advantage of passing arguments by reference is that the function can access the actual variables in the calling program. Among other benefits, this provides a mechanism for passing more than one value from the function back to the calling program.

To pass arguments by reference, we use the ampersand (&). The formats are:

Type function_name function name(Type &par); // declaration


or

Type function_name _ (Type &); // declaration Type function_name(Type &par) // definition


{

function body
}

Sample program
# #include <iostream.h> void swap(int &x, int &y); int main() { int x = 5, y = 10; cout << "Main. Before swap, x:" << x << " y: " << y; swap(x, y); cout << "Main. After swap, x:" << x << " y: " << y; return 0; } void swap (int &rx, int &ry) { int temp; cout << "Swap. Before swap, rx:" << rx << " ry:" << ry; temp = rx; rx = ry; ry = temp; cout << "Swap. After swap, rx:" << rx << " ry:" << ry; }

Output Main. Before swap, x: 5


Swap. Before swap Swap swap, rx: 5 Swap. After swap, rx: 10 Main. After swap, x: 10

y: 10 ry: 10 ry: 5 y: 5

Using Pointers as arguments to Functions


There are th Th three ways t to pass arguments t to t a function: f ti by b value, by reference, and by pointer. If the function is intended to modify variables in the calling program, program then these variables cannot be passed by value, since the function obtains only a copy of the variable. variable However, However either a reference argument or a pointer can be used in this situation. Passing a pointer as an argument to a function is in some ways similar to passing a reference. They both permit the variable in the calling program to be modified by the function. However, the mechanism is different. A reference is an alias for the original variable, while a pointer is the address of the variable.

Sample program
#include <iostream.h> void centimize(double int main() { double var = 10.0; cout << "var = " << centimize(&var); cout << "var = " << return 0; } void centimize(double { *ptr *= 2.54; } *);

var << " inches" << endl; var << " cm" << endl;

*ptr)

Output var = 10 inches var = 25.4 cm

Passing Arrays to Functions


In a function I f ti definition, d fi iti a parameter t that th t is i declared d l d as an array is a pointer. When an array is being passed, its base address is passed. The array elements themselves are not copied. As a notational convenience, the compiler allows array bracket notation to be used in declaring pointers as parameters. This notation reminds i d the th programmer and d other th readers d of f the th code d that th t the function should be called with an array. To illustrate this, we e write rite a f function ctio that th t sums s ms the eleme elements ts of an array rr of type int:

int sum(int a[], int n) // n is the size of a[] { int s = 0; for (int i=0; i<n; i++) s += a[i]; return s; }

As part of the header of a function definition, the declaration (int i t a[] []) i is equivalent i l t to t (int i t *a * ). ) In I other th contexts, t t the th two are not equivalent.

N t Note
You do not, and should not, put a number in the square brackets in the argument list of either the prototype or the function header.

Suppose that v has been declared to be an array with 100 elements of type int. After the elements have been assigned values, we can use the function sum() to add various elements of v. Here are some of the possibilities:
sum(v, 100); sum(v, ( 88) 88); sum(v+7, 10); int *p p = v; sum(p, 100); // v[0] + v[1] + . . . + v[99] // v[0] [0] + v[1] [1] + . . . + v[87] [87] // v[7] + v[8] + . . . + v[16] // v[0] + v[1] + . . . + v[99]

Overloading Functions
C++ enables bl you to t create t more than th one function f ti with ith the th same name. This is called function overloading. The functions must differ in their parameter list, list with a different type of parameter, a different number of parameters, or both. Here's Here s an example:
int myFunction(int); y ( , int); ); int myFunction(int, float myFunction(float, float); int max(int, int); d bl max(double, double (d bl d bl ) double);

The return types can be the same or different on overloaded f functions. i You Y should h ld note that h two f functions i with i h the h same name and parameter list, but different return types, generate a compiler error. error

Sample program
#include <iostream.h> int area(int x); i t area(int int (i t x, int i t y); ) double area(double x); double area(double x, double y); y int main() { cout << area(12) << endl; cout << area(12, 15) << endl; cout << area(12.5) << endl; cout << area(12.5, 16.75) << endl; return 0; }

int area(int x) { cout << "Called area with 1 int argument: "; return x * x; } int area(int x, int y) { cout << "Called Called area with 2 int arguments: "; ; return x * y; } double area(double x) { cout << "Called area with 1 double argument: "; return x * x; } double area(double x, double y) { cout << "Called area with 2 double arguments: "; return x * y; }

Output
Called Called Called Called area area area area with with with with 1 2 1 2 int argument: 144 int arguments: 180 double argument: 156.25 double arguments: 208.75 208

Recursion
Recursion occurs when a function calls itself directly or indirectly. A recursive function must follow two basic rules: It must have an ending point. It must reduce the amount of work to be done each time i ' called. it's ll d Some functions lend themselves naturally to recursive algorithms such as the factorial. algorithms, factorial A definition of factorial is: fact(0) = 1 fact(n) = n * fact(n-1) In C++, this definition translates to: int fact(int ( number) ) { if (number == 0) return (1); ( ); return (number * fact(number-1)); }

Sample program
#include <iostream.h> unsigned int fact(unsigned int number) { if ( (number == 0) ) return (1); return (number * fact(number-1)); } int main() { int n; do { cout << "Enter Enter a number: "; ; cin >> n; if (n < 0) return 0; cout << "Factorial is " << fact(n) << endl; } while (n >= 0); return 0; }

User-Defined Data Types


The typedef Statement Enumeration Structures Declaring a Structure Declaring Variables of The Structure Accessing Structure Members Initializing a Structure Variable

The typedef Statement


When you write Wh it a program you will ill want t t to represent t th the data you wish to manipulate in such a way that makes it clear to you and to others what you are doing. doing The data also should be modeled in a manner that best suits the problem. The typedef keyword lets you declare an alternate name for an existing data type. Thus, typedef does not define a new data type, but merely another name for an existing type. The typedef statement has the following format.
typedef old_type old type new new_type type;

Examples:
typedef float Currency; typedef int Hours; typedef unsigned short int USHORT;

The first example declares a type synonym for the float data type called Currency. Currency is now just another name for a float. The second example declares a synonym for int named Hours, , and the third example p creates the new name USHORT that you can use anywhere you might have written g short int. unsigned To understand how to use typedef, it is best to consider an example. p Ap program g that manipulates p money y amounts would use variables of type double to represent these amounts. Such a program might contain the following declarations:
double value, amount;

A person reading di thi this program might i ht not t know k that th t th the variables value and amount represent money amounts.

Suppose instead that we declare the variables as follows:


typedef double MONEY_AMOUNT; MONEY AMOUNT; MONEY_AMOUNT value, amount;

The typedef statement makes the identifier MONEY_AMOUNT equivalent to the type double. Therefore, you are allowed to d l declare variables i bl of ft type MONEY_AMOUNT O O . The Th C++ compiler il translates a declaration of type MONEY_AMOUNT as though it is a declaration of type double. By using the type MONEY_AMOUNT, the variable declarations give information about the kind of number that the variables represent. represent

Sample program
#include <iostream.h> <iostream h> typedef unsigned short int USHORT; int main() { USHORT Width = 5; USHORT Length; Length = 10; USHORT Area = Width * Length; cout << "Width: Width: " << Width << endl; cout << "Length: " << Length << endl; cout << "Area: " << Area << endl; return 0; }

Output
Width:5 g 10 Length: Area: 50

Enumeration
When programming, Wh i you will ill encounter t many situations it ti where code clarity can be improved by referring to integer values by a meaningful name rather that just the integer value itself. An enumerated data type is a new type that you declare and assign possible integer value states that are referred to by name. The syntax for creating enumerated constants is to write the keyword enum, followed by the new type name, an opening brace each of the legal values separated by a comma, brace, comma and finally, a closing brace and a semicolon. Here is an example:
enum EyeColor {Blue, Green, Brown, Black};

This statement performs two tasks:

It makes EyeColor the name of an enumeration; that is, is a new type. It makes Blue a symbolic constant with the value 0, Green a symbolic constant with the value 1, Brown a symbolic y constant with constant with the value 2, Black a symbolic the value 3.

The type name EyeColor can now be used to declare a variable that can hold one of the four possible EyeColor state values:
EyeColor my_eye_color;

The variable my y_eye y _color can be assigned g any y one of the following values: Black, Hazel, Blue, or Brown. Observe the following line of code:
my_eye_color = Brown;

The nice thing about enum types is that the compiler will you are only y assigning g g one of the valid state values to ensure y the enum variable. For instance, the following line of code will produce a compiler error:
my_eye_color = 6; //Error...6 is an int not an //EYE_COLOR

Every enumerated constant has an integer value. If you dont specify otherwise, the first constant has the value 0, and the rest count up from there. Any one of the constants can be initialized with a particular value, however, and those that are not initialized count upward from the ones before them. Thus, if you write
enum EyeColor{GREEN=100, BLUE, BROWN=500, BLACK};

RGREEN has the value 100; BLUE, the value 101; BROWN, the value 500; and BLACK, the value 501.

Although the values associated with the EyeColor enum states may not be important, there are cases where an enum enums s state values might be a concern. Examine the following enum declaration:
enum Package {Single = 1, SixPack = 6, TwelvePack = 12, 12 EconoPack = 24};

In this example the enum Package has four states, each with a non-default, d f lt non-consecutive ti value. l

Enumerated types can be used with switch statements to improve their readability. Observe the following example:
switch (my_eye_color) { case Green: cout << "You have break; case Blue: cout << "You have b break; k case Brown: cout << "You have break; case Black: cout << "You You have break; default: cout << "You have }

green eyes!" << endl;

blue eyes!" << endl;

brown eyes!" << endl;

black eyes! eyes!" << endl;

? eyes!" << endl;

Sample program
#include <iostream.h> int main() { enum Days {Sun=1, {Sun 1, Mon, Tue, Wed, Thu, Fri, Sat}; Days today; int d; cout << "Enter the number of today: " << "1=Sunday ... 7=Saturday\n"; cin >> d; today = Days(d); if (today == Fri || today == Sat) cout << "I love the weekends!\n"; else if (today >= Sun && today <= Thu) cout << "I hate work days!\n"; else cout << "Wrong number!\n"; return 0; }

Variables of an enumerated type can be given any of the values listed in the enum declaration. enum Days {Sun=1, Mon, Tue, Wed, Thu, Fri, Sat}; y day1, y day2; y Days day1 = Mon; day2 = Thu; You cant use values that werent listed in the declaration. Such statements as
day1 = halloween;

are illegal. The enumerated constant could be replaced with a series of constant integers as shown in the following program, but using enumerations rather than integer constants can make programs p g clearer and more maintainable.

#include <iostream.h> int main() { const int Sun = 1, Mon = 2, Tue = 3, Wed = 4, Th = 5, Thu 5 Fri F i = 6 6, Sat S t = 7; 7 int today; cout << "Enter the number of today: " << "1=Sunday ... 7=Saturday\n"; cin >> today; if (today == Fri || today == Sat) cout << "I love the weekends!\n"; else if (today >= Sun && today <= Thu) cout << "I hate work days!\n"; else cout << "Wrong number!\n"; return 0; }

CAUTIONS
A Assigning i i th the i integer t equivalent i l t of f an enumeration ti constant t t to a variable of the enumeration type is a compilation error. After an enumeration constant has been defined defined, attempting to assign another value to the enumeration constant is a compilation error.

Structures
Arrays allow the programmer to define variables that combine several data items of the same kind. Suppose we want to process inventory information on parts that are stored in a warehouse. For each part, we would like to store the part number (a seven character code), the quantity (an integer), and the unit price (a double). We could declare a variable for each of these quantities.
char model_no[8]; int quantity; double price;

However, doing so does not reflect that the three variables contain values that are associated with a particular part. part We need a single variable in which we can store all three quantities. For this purpose the structure can provide this capability.

Declaring a Structure
The following declares a structure that we can use to solve our inventory problem:
struct PART_STRUCT PART STRUCT { char model_no[8]; i int quantity; i double price; };

The declaration begins with the keyword struct. The identifier PART_STRUCT PART STRUCT gives a name to the structure. (We place the suffix _struct at the end of a structure name to remind us that the identifier is a structure. This is not required by C++, but is a useful programming practice.) Following the structure name are the structure members enclosed in braces. braces The close curly brace must be followed by a semicolon.

The structure members are the parts of the structure and y are declared in the same way y as ordinary y variables they although they are not variables. The PART_STRUCT structure has three members. The first member, model_no, is a character array. The second member, quantity, is an integer. The third member, price, is a double. Note that the d fi iti of definition f the th structure t t ends d in i a semicolon. i l It is important to realize that the declaration of the PART STRUCT structure PART_STRUCT t t does d not t declare d l a variable. i bl It, It therefore, does not reserve any space in computer memory. A structure declaration defines a template for the compiler to use when we declare PART_STRUCT variables. As with enum, y defines another data type. yp By y the struct statement actually itself it does not declare a variable. Also, the model_no, quantity, and price are merely names for the members of the structure and are not variables.

Declaring Variables of The Structure


To declare a variable that is of the PART_STRUCT PART STRUCT type, type we can code the following:
PART STRUCT part; PART_STRUCT

This declaration delares a variable, part, that is of the data type PART_STRUCT PART STRUCT. Internally, Internally the variable part has the structure that we defined in the struct statement for PART_STRUCT _ . Although the PART_STRUCT data type does not reserve computer storage, the variable part does. The variable part requires i whatever h amount of f storage i is necessary to store an eight-character array, an integer, and a double. You also can declare multiple variables ariables of the structure or an array: PART STRUCT part1 PART_STRUCT part1, part2, part2 part3; PART_STRUCT part[100];

Accessing Structure Members


Now that we have declared a structure variable, variable how can we access the members of that variable? For example, how can we assign g the value 62 to the q quantity y member of p part? To access a member of a structure, we must use the member operator. The member operator is coded as a period between the h structure variable i bl name and d the h structure member b that h we wish to access. Thus, we refer to the quantity member of part as part.quantity. part quantity To assign 62 to this member, member we would code the following: part.quantity = 62; We can also use cin to enter a value by the user: cin >> part.quantity; part quantity; Similarly, you could output the value of the member variable using the same syntax: cout << part.quantity;

Dont make the beginners mistake of using the name of the , rather than the name of the structure variable, , as structure, in the following example:
PART STRUCT.quantity = 62; // error! PART_STRUCT.quantity

You may declare a structure variable essentially anywhere in your program; the same scope and lifetime rules apply just the way they do for int, float, and other types of variables.

Initializing a Structure Variable


You can initialize a structure variable similarly to the way in which you initialize an array. For example, using the yp defined earlier, , we can declare and PART_STRUCT data type initialize the variable old_part as follows:
PART STRUCT old PART_STRUCT old_part part = { {"XY98765", XY98765 , 17, 99.99};

Thus, to initialize a structure variable, enclose in braces a list of the structure member values. values Separate the values by commas. You must take care that the types of the values in p to the data types yp of the members of the the list correspond structure. Thus, in our example, the first listed value is a string, the second value is an integer, and the third value is a double.

A structure is a powerful tool because it allows you to group g y related data under a single g name. What is even more logically interesting is that a structure can also be passed into a function. This is of particular use when you have several variables that need to be passed into a function. Passing more than three or four variables to a function can be convoluted and confusing. confusing It becomes an exceedingly inelegant-looking inelegant looking program. However, you can pass a single variable, a structure pieces of data y you require. q that contains all the various p Passing them in a structure can be very convenient. As was previously stated, you can use a structure just like any other data type. This means that not only can it be passed to a function as an argument, but also it can be returned. This can b very useful. be f l Recall R ll that th t f functions ti can only l return t a single i l item. What if your function needs to give back several pieces of data? Returning a structure will allow that to happen. happen The following example illustrates this concept.

#include <iostream.h> #include <math.h> <math h> const double pi = 3.14159; struct geometry_data { float radius; double angle; }; struct geometry_answers geometry answers { float area; d bl sine; double i double cosine; double tangent; }; geometry answers compute(geometry_data geometry_answers compute(geometry data mystruct);

int main() { geometry_data input; geometry_answers output; cout << "Enter Enter the radius of the circle: "; ; cin >> input.radius; cout << "Enter the angle in degrees: "; cin >> input.angle; input.angle *= pi / 180; output = compute(input); cout << " The area is "<< output.area << endl; cout << " The sine of the angle is " << output.sine i << endl; dl cout << " The cosine of the angle is " << output.cosine p << endl; ; cout << " The tangent of the angle is " << output.tangent << endl; return t 0 0; }

geometry_answers compute(geometry_data mystruct) { geometry_answers answer; answer.area = pi * pow(mystruct.radius,2); answer.sine = sin(mystruct.angle); answer.cosine = cos(mystruct.angle); answer.tangent = tan(mystruct.angle); return answer; }

Classes
What Are Classes? Declaring a Class Calling Data Member and Member Functions Assign Values to Objects, Not to Classes Using Access Specifiers Class Members Are Private by Default Private and Public Data Memory Allocation Creating Methods Constructor and Destructor Separating Classes into Files P i t Pointers To T Obj Objects t Arrow Operator Static Class Members

Object-Oriented Programming
Object-Oriented Obj t O i t d Programming, P i often ft known k by b its it acronym, OOP , is a term used more than it is understood. However, understanding OOP principles is important, important since OOP really is the next step. Indeed, the previous chapters have given you the foundation to learn OOP . While game programs are fun, the usual purpose of a program is to provide a solution to real real-world world tasks, which involve persons, places, things, or concepts. Programs use j to represent p a real-world p person, , p place, , thing, g, or objects concept. j simplify p y the real-world things g they y represent. p Just as Objects you dont need to know how an internal combustion engine works to drive a car, you dont need to understand the inner workings of the object to know how to use it.

You are a person object. This book is a book object. The car you drive is a car object. y j A character in a g game also is an object. The number and variety of possible objects is unlimited. If you already have created a person class and you write the teacher class, you dont need to write code for those attributes tt ib t that th t a teacher t h has h in i common with ith all ll persons, such as a name, birthday, height, weight and so forth. Rather, the teacher class can inherit inherit those attributes from the person class, so you only need to write code for those attributes that a teacher has in addition to, or different than, all persons generally, such as tenure status, a higher education level, and so on. This ability of one class to inherit from another is called, inheritance. Inheritance enables you to reuse existing code, such as the person class, class when creating classes that represent more specialized objects, like teachers.

Code reusability makes application development faster since you dont have to reinvent the wheel. Additionally, y y, the applications you develop are less buggy since the code you are reusing already has been tested (hopefully). Since structures and classes are heavily used in OOP , lets discuss them now.

What Are Classes?


Classes extend Cl t d the th built-in b ilt i capabilities biliti of fC C++ t to assist i t you in representing and solving complex, real-world problems. You make Y k a new type b by declaring d l i a class. l A class l i is j just a collection of variables combined with a set of related functions. functions A class can consist of any combination of the variable types and also other class types. t pes The variables ariables in the class are referred to as the member variables or data members. The functions in the class typically manipulate the member variables. They are referred to as member functions or methods of the class. A class enables you to encapsulate these variables and functions into one collection, which is called an object.

Declaring a Class
To declare T d l a class, l use th the class keyword k d f followed ll d by b an opening brace, and then list the data members and methods of that class. class End the declaration with a closing brace and a semicolon. The following code is the general syntax for declaring a class. class
class ClassName {

memberList
};

Here ClassName is the name of the class, , and memberList is the list of class members.

memberList consists of a list of member declarations. These


can be data member or method declarations. declarations Data member declarations are normal variable declarations. For example, example int i t x; is a data member declaration when inside a class. However, you cannot initialize data members where you declare them. them They must be initialized either in a method or outside the class. For example, int x = 50; as a data member declaration causes an error. error Method declarations are function declarations placed inside a class (recall that a function declaration can also include the implementation, or you can implement it separately). All methods can be accessed only through an object of the class.

Example: class Part { int modelnumber; double cost; void SetPart(int mn, double c); void ShowPart(); (); };

Defining an Object
An object is an individual instance of a class. You define an object of your new type just as you define an integer variable (or any other variable): P t wheel; Part h l This code defines wheel, which is an object whose class (or t type) ) is i Part P t.

Calling Data Member and Member Functions


Once you d O define fi an actual l Part object bj -for f example, l wheelyou use the dot operator (.) to access the members of that object. bj t Therefore, to assign 50 to wheels modelnumber member variable, i bl you would ld write it wheel.modelnumber = 50; In the same way, to call the ShowPart() function, you would write wheel.ShowPart(); When y you use a class method, , y you call the method. In this example, you are calling ShowPart() on wheel.

Assign Values to Objects, Not to Classes


In C++ you don't assign values to types; you assign values to variables. For example, you would never write
int = 50; //wrong

The compiler would flag this as an error, error because you can can't t assign 50 to an integer. Rather, you must define an integer variable and assign 50 to that variable. For example,
int x; //define x to be an int x = 50; //set x's x s value to 50

This is a shorthand way of saying, "Assign 50 to the variable x, which hi h i is of ft type int i ". "

In the same way, you wouldn't write


Part.modelnumber d l b = 50; 50 //wrong // ???

The compiler would flag this as an error, because you can't assign i 50 to the h modelnumber of f a Part. Rather, h you must define a Part object and assign 50 to the modelnumber of th t object. that bj t

For example:
Part wheel; //just like int x; wheel.modelnumber = 50; //just like x = 50;

Using Access Specifiers


C++ allows C ll you t to control t l where h the th data d t members b of f your class can be accessed. This control is a powerful tool because it allows you to protect data members from accidental. accidental An access specifier is a word that controls where the data members in a class can be accessed. The syntax for an access specifier is as follows:
c ass C class ClassName ass a e { classMembers;

accessSpecifier S ifi : classMembers;


};

An access specifier affects all members of the class (including p is methods) that come after it until another access specifier encountered or until you reach the end of the class.

A class has two kinds of access specifiers: public and private.

public members can be accessed anywhere that an object of the class can be accessed and from within the class (that is, is in the classs methods). private members can be accessed only from within the class itself. An object of the class cannot access the private members except through public methods. members, methods If no access specifier is provided in the class, all members default to private.

Here is an example of how you might use these specifiers:


class ClassName { int x; public: int y; int z; private: int a; };

In this example, p , x and a are p private members, , and y and z are public. You may have as many access specifiers as you want in your classes.

Class Members Are Private by Default


In the I h class Part declaration d l i example l modelnumber, cost, SetPart(), and ShowPart() are all private, because all members of a class are private by default. default This means that unless you specify otherwise, they are private. Therefor, if you write
Part wheel; wheel.modelnumber = 50; //error //

the compiler flags this as an error, because modelnumber is private, and you can can't t access private data. The way to use wheel so that you can access the data members is to declare it public.

class Part { public: int modelnumber; double cost; void SetPart(int mn, double c); void ShowPart(); };

Now modelnumber, cost, SetPart(), and ShowPart() are all public. And wheel.modelnumber wheel modelnumber = 50; compiles without problems.

Private and Public Data


Usually the data within a class is private and the functions are public. This is a result of how classes are used. The data p , is hidden so it will be safe from accidental manipulation, while the functions that operate on the data are public so they can be accessed from outside the class. However, there is no rule that data must be private and functions public; in some circumstances you may find youll need to use private functions and public data. data class Part { private: int modelnumber; double cost; public: void SetPart(int mn, double c); void id ShowPart(); h () };

#include <iostream.h> class Part { private: int modelnumber; double cost; public: void SetPart(int mn, double c) //set data { modelnumber = mn; ; cost = c; } void ShowPart() //display data { cout << "Model " << modelnumber; cout << ", costs $" $ << cost << endl; } } };

int main() { Part part1, part2, part3; part1.SetPart(6245, 220); part2.SetPart(6246, t2 S tP t(6246 185); 185) part3.SetPart(6247, 150); p part1.ShowPart(); (); part2.ShowPart(); part3.ShowPart(); return 0; }

Output
Model 6245, costs $220 Model 6246, costs $185 Model 6247, costs $150

Memory Allocation
Declaring D l i this thi class l doesn't d 't allocate ll t memory for f a Part P t . It just tells the compiler what a Part is, what data it contains (modelnumber and cost), ) and what it can do (SetPart() and ShowPart()). It also tells the compiler how big a Part is (that is, , how much room the compiler p must set aside for each Part that you create). In short, specifying a basic type does two things: It determines how much memory is needed for a data object. It determines what operations, or methods, can be performed using the data object.

Each new object you create contains storage for its own i internal l variables, i bl the h class l members. b B But all ll objects bj of f the h same class share the same set of class methods, with just one copy of each method. method

Creating Methods
Each E h function f ti that th t you declare d l for f your class l must t have h a definition. The definition is also called the function implementation Like other functions, implementation. functions the definition of a class method has a function header and a function body. You can declare a method two ways. ways The most common way is to declare a method inside the class declaration and then implement it outside. The second way is to declare and implement the method at the same time inside the class declaration. You should declare most of your methods the first way. , there is special p syntax y for the method definition. A However, member function definition begins with the return type, followed by the name of the class, two colons (::), the name of the function, and its parameters.

Here is the general syntax for a method implementation that occurs outside a class:

return_typ ClassName::methodName(parameterList)
{

methodImplementation;
}

Here ClassName is the name of the class, and methodImplementation is the code that goes inside the method. As you can see, this syntax is very similar to the f function i definition d fi i i syntax. The Th double d bl colon l (::) is i called ll d the scope resolution operator. Here you are telling the computer to use the classs scope by putting the classs name in front.

Constructor and Destructor


Two special T i l kinds ki d of f methods, th d the th constructor t t and d the th destructor, can be in a class. Both are optional, but they provide special functionality that other methods cannot provide. A constructor is executed every time a new instance of the class is created -that is, every time you declare a new object-. The constructor is normally used to set initial values for the data members. A constructor always has the same name as the class and cannot have a return value (not even void). A destructor is the opposite of a constructor and is executed when the object is destroyed. The destructor is always named the h same name as the h class, l b but with i h a tilde ild ( (~) ) at the h beginning. The destructor cannot have arguments or a return value A destructor is often used to perform any necessary value. cleanup tasks.

Both constructors and destructors are like methods; they can be declared and implemented at the same time or declared and implemented separately. Here is the syntax for declaring p g at the same time: and implementing
class ClassName { //constructor ClassName([argumentList]) { implementation; } //destructor ~ClassName() { implementation; } //other members // };

Here is the syntax for declaring and then implementing:


class l ClassName Cl N { ClassName([argumentList]); ~ClassName(); //other Members };

ClassName::ClassName([argumentList])
{

implementation;
}

ClassName::~ClassName()
{

implementation;
}

Notice that the constructor can have arguments. If you create a constructor with arguments, the user of your class must supply values for these arguments when creating an object. The destructor, on the other hand, cannot have arguments. It is called automatically, so there isnt necessarily a chance for provide arguments. g the user to p Because a constructor can have arguments, it might become y to overload the constructor. This is legal g in C++ necessary and is quite common in large classes. Overloading the constructor in this way gives your class versatility and provides users of the class with many options. The destructor cannot be overloaded. Having no return type or arguments, there is nothing with which the destructor can be overloaded.

// Example 1: constructor without parameters #include <iostream.h> class Part { private: int modelnumber, quantity; double cost; public: bli Part() //constructor no parameters { quantity = 100; } ~Part(){} Part(){} //destructor void SetPart(int mn, double c) { modelnumber = mn; cost = c; }

void ShowPart() { cout << "Model " << modelnumber; cout << ", quantity " << quantity; cout << ", costs $" << cost << endl; } }; int t main() a () { Part part1, part2; part1 SetPart(6245 220); part1.SetPart(6245, part2.SetPart(6246, 185); part1.ShowPart(); part2 ShowPart(); part2.ShowPart(); return 0; }

Output
Model 6245, quantity 100, costs $220 Model 6246, quantity 100, costs $185

// Example 2: constructor with parameters #include <iostream.h> class Part { private: int modelnumber, quantity; double cost; public: bli Part(int q) //constructor with parameter { quantity = q; } ~Part(){} Part(){} //destructor void SetPart(int mn, double c) { modelnumber = mn; cost = c; }

void ShowPart() { cout << "Model " << modelnumber; cout << ", quantity " << quantity; cout << ", , costs $ $" << cost << endl; ; } }; int main() { Part part1(320), part2(240); part1 SetPart(6245 220); part1.SetPart(6245, part2.SetPart(6246, 185); part1.ShowPart(); part2.ShowPart(); t2 Sh P t() return 0; }

Output
Model 6245, , q quantity y 320, , costs $ $220 Model 6246, quantity 240, costs $185

// Example 3: constructor with overloading #include <iostream.h> class Part { private: i t modelnumber, int d l b quantity; tit double cost; public: P t() //constructor Part() // t t no parameters t { quantity = 100; } Part(int q) //constructor with parameter { quantity = q; } ~Part(){} //destructor void SetPart(int mn, double c) { modelnumber = mn; cost = c; }

void ShowPart() { cout << "Model " << modelnumber; cout << ", quantity " << quantity; cout << ", , costs $ $" << cost << endl; ; } }; int main() { Part part1, part2(200); part1 SetPart(6245 220); part1.SetPart(6245, part2.SetPart(6246, 185); part1.ShowPart(); part2.ShowPart(); t2 Sh P t() return 0; }

Output
Model 6245, quantity 100, costs $220 Model 6246, quantity 200, costs $185

Separating Classes into Files


Classes often Cl ft get t pretty tt big, bi and d having h i all ll your code d in i one file can quickly become unmanageable. Also, if you want to reuse your classes in other programs, programs you have to copy and paste them into the new program. Fortunately, there is a convention for separating classes into files. Normally, the class declaration is placed in one file (header file), and the implementation of all the methods is put in another file. The class declaration file is normally called ClassName.h, where ClassName is the name of the class. The implementation file is normally called ClassName.cpp. Then you include the header file in your program with an #include #i l d directive. directive The syntax for the #include directive is as follows:
#include "filename"

However, instead of including two files (ClassName.h and pp), y you have to include only y ClassName.h. The ClassName.cpp), compiler will include the .cpp file automatically (provided that the two files are in the same directory). Here is how the Part class looks separated into different files:
//Part.h //Part h class Part { private: int modelnumber, quantity; double doub e cost; public: Part(int q); ~Part(); void SetPart(int mn, double c); void ShowPart(); };

//Part.cpp #include <iostream.h> #include "Part.h" "Part h" Part::Part(int q) { quantity = q; } P t Part::~Part() P t() { } void Part::SetPart(int ( mn, double c) ) { modelnumber = mn; cost = c; } void Part::ShowPart() { cout << "Model " << modelnumber; cout << ", q quantity y " << q quantity; y cout << ", costs $" << cost << endl; }

//Main.cpp #include "Part.h" int main() { Part part1(150), part2(200); part1.SetPart(6245, 220); part2.SetPart(6246, 185); part1.ShowPart(); part2 ShowPart(); part2.ShowPart(); return 0; }

Output
Model 6245, quantity 150, costs $220 Model 6246, quantity 200, costs $185

Example:
// DeckOfCards.h #ifndef CARDS_GAME #define CARDS_GAME struct Card { char h * it *suit; char *face; }; class DeckOfCards { Card deck[52]; public: DeckOfCards(); ec O Ca ds(); void shuffle(); void deal(); }; #endif

//DeckOfCards.cpp #include <iostream.h> #incl de <iomanip.h> #include <iomanip h> #include <time.h> #include "DeckOfCards.h" DeckOfCards::DeckOfCards() { char h * it[4] = *suit[4] {"Hearts", "Diamonds", "Clubs", "Spades"}; char *face[13] = {"Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}; //set values for deck of 52 Cards for (int i=0; i<52; i++) { deck[i].suit = suit[i / 13]; deck[i].face = face[i % 13]; } srand(time(0)); }

void DeckOfCards::shuffle() { // h ffl cards //shuffle d randomly d l for (int i=0; i<52; i++) { i t j = rand() int d() % 52; 52 Card temp = deck[i]; deck[i] = deck[j]; d k[j] = temp; deck[j] } } void DeckOfCards::deal() { //display each card's face and suit for (int i=0; i<52; i++) { cout << right << setw(5) << deck[i].face << " of " << left << setw(8) << deck[i].suit << endl; if ((i + 1) % 13 == 0) cout << endl; } }

//Main.cpp #include "DeckOfCards.h" DeckOfCards.h int main() { DeckOfCards deckOfCards; deckOfCards.shuffle(); deckOfCards.deal(); return 0; }

Pointers To Objects
An object A bj t of f a class l has h a memory addressjust dd j t lik like any other object. You can assign this address to a suitable pointer. For example, example suppose we have declared a class called Account and we want to define an object of this calass: Account savings( savings("Mac, Mac, Rita Rita",654321, ,654321, 123.5); Account *ptrAccount = &savings; This defines the object j savings g and a p pointer variable called ptrAccount. The pointer ptrAccount is initialized so that it points to the object savings. This makes *ptrAccount the object savings itself. You can then use the statement
(*ptrAccount).display();

to call the method display() for the object savings. Parentheses must be used in this case, as the operator . has higher precedence than the * operator.

Arrow Operator
You can use th Y the class l member b access operator t (-> >) (in (i short: h t arrow operator) instead of a combination of (*) and (.) .
objectPointer->member; bj tP i t b

This expression is equivalent to


(*objectPointer).member;

The operator -> > is made up of a minus sign and the greater than sign. a p e: Example:
ptrAccount->display();

This statement Thi t t t calls ll th the method th d display() di l () for f the th object bj t referenced by ptrAccount, that is, for the object savings. The statement is equivalent to the statement in the previous example.

The difference between the class member access operators (.) and (-> >) is that the left operand of the dot operator must be an object, whereas the left operand of the arrow operator must be a pointer to an object.

Example1: pointers to objects


#include <iostream.h> class Part { private: int modelnumber, quantity; double cost; p public: Part() { quantity q y = 100; ; } Part(int q) { quantity = q; } void SetPart(int mn, double c) { modelnumber = mn; cost = c; }

void ShowPart() { cout << "Model " << modelnumber; cout << ", quantity " << quantity; cout << ", costs $" << cost << endl; } }; int main() { Part *part1, *part2; part1 = new Part; p ; part2 = new Part(200); part1->SetPart(6245, 220); part2->SetPart(6246 part2 >SetPart(6246, 185); part1->ShowPart(); part2->ShowPart(); delete part1; delete part2; return 0; }

Example2 : pointers to objects (dynamic arrays)


//Part.h #ifndef PART #define PART #include <iostream.h> class Part { private: int modelnumber, quantity; double cost; public: bli void Init(int mn, int q, double c); void SetQuantity(int y q); q void SetCost(int c); void ShowPart(); } #endif

//Part.cpp #include "Part.h" void Part::Init(int mn, mn int q, q double c) { modelnumber = mn; SetQuantity(q); SetCost(c); } void Part::SetQuantity(int q) { quantity = q; } void Part::SetCost(int c) { cost t = c; } void Part::ShowPart() { cout << "Model " << modelnumber; cout << ", quantity " << quantity; cout << ", costs $" << cost << endl; }

//Main.cpp #include "Part.h" i int main() i () { Part *part; int n, n mn, mn q, q i; double c; cout << "Enter the number of parts: "; cin >> n; part = new Part[n]; for (i=0; i<n; i++) { cout << "\nEnter model number for part#" << i+1 << ": "; cin >> mn; cout << "Enter quantity for part#" << i+1 << ": "; cin >> q; cout t << "E "Enter t cost t f for part#" t#" << i+1 << " ": " "; cin >> c; part[i].Init(mn, q, c); } cout << endl;

for (i=0; i<n; i++) { part[i].ShowPart(); } delete[] part; return 0; }

Static Class Members


Every object has its own characteristics. characteristics This means that the data members of two different objects will be stored at different memory addresses. However, sometimes it is useful to keep some common data that can be accessed by all the objects belonging to a class, for example: figures such as exchange rates, interest rates or time limits which have the same value for every object status t t information, i f ti such h as the th number b of f objects, bj t minimum or maximum values. This kind of data needs to be stored only once, no matter how many objects exist. Since a programmer will also need to manage the data from within the class, it should be represented within the class rather than globally. Static data members can be used for this purpose. In contrast to normal d t members, data b static t ti data d t members b occur only l once in i memory.

Declaration
Static data members are declared within a class, class the keyword static is used to declare members of this type. Example: a p e:
static double min, max; // Declaration

Definition and Initialization


Static data members occupy memory space even if no objects y must be defined and of the class have been created. They initialized in an external source file. The range operator (::) is then used to relate the data members to the class. Example:
double Result::min = 0.0; // Definition

As the example illustrates, the static keyword is not used during the definition. Static data members and member functions belonging to the same class are normally defined in one source file.