Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web...

49
Introduction and basic C++ programming Getting Started: Attendance Syllabus Handouts – bloodshed c++ & turingscraft/codelab Compiler – bloodshed c++ on my webpage url to download the free compiler. Code Lab Steps to enroll in and start using turning's craft Go to the following address: http://www.turingscraft.com/ click on register student continue your access code is CUN-BRO-6465-2210 university is CUNY-brooklyn document.doc 1 of 49

Transcript of Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web...

Page 1: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Introduction and basic C++ programming

Getting Started:

Attendance

Syllabus

Handouts – bloodshed c++ & turingscraft/codelab

Compiler – bloodshed c++ on my webpage url to download the free compiler.

Code Lab

Steps to enroll in and start using turning's craft

Go to the following address:

http://www.turingscraft.com/

click on register

student

continue

your access code is CUN-BRO-6465-2210

university is CUNY-brooklyn

type in the email address you want to use (real)

select a password

enter your first and last names

document.doc 1 of 37

Page 2: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

accept the agreement

you are taken to the exercises

please start working on them – I will put up due dates

also, please let me know if the process works

document.doc 2 of 37

Page 3: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

High-level - Compiler Languages (closer to human languages – assembly low level – closer to machine language)

More English-like, more natural. Each high-level language statement translates to several low-level language statements. Use compilers to translate from the high-level language into machine language. Compilers translate the whole program first, then execute the object program.

A compiler language is a high-level language which is machine-independent.

High-level languages are more English-like, easier to code, more costly to run, less flexible. e.g., FORTRAN, BASIC, COBOL, PL/1, ALGOL, APL, Pascal, SIMSCRIPT, Smalltalk, C, C++, Java.

A compiler is a translator program that transforms high-level program code into a low-level machine-level executable program.

document.doc 3 of 37

compileror interpreter

source program

object program

Page 4: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

C++ Programming

Every programming language has facilities to: in C++

1. Read data from some input device cin >>

2. Write output information onto an output device cout <<

3. Perform arithmetic operations + - * /

4. Perform relational operations < == >

5. Perform logical operations ! && ||

6. Branch to a non-sequential instruction (w/wo structure) while

7. Store (and retrieve) data values to (and from) memory =

document.doc 4 of 37

Page 5: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Homework

Running a simple C++ program in Bloodshed Dev-C++

Bloodshed Dev-C++ provides an integrated environment for writing programs. "Integrated environment" means Dev-C++ is a combination program, consisting of a text editor and a C++ compiler. A text editor is a limited word processing program that allows you to type in your program, make corrections and changes, and save and retrieve your program from disk storage. The editor is integrated with the Dev-C++ compiler so that you can easily switch between editing your program and compiling and running it. Note that the Dev-C++ compiler allows you to write, compile and run programs in either C or C++.

When you are in the Dev-C++ environment,

1. Select File | New | Source file.

2. Type in program

document.doc 5 of 37

Page 6: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

3. Right BEFORE the line that says return 0;  type this:    system("pause");                  (pause can be lowercase or caps)This line will keep the output window open when the program has finished executing. 

Enter the following program into the program1.cpp file window.Every C++ program we write will start with a comment followed by these three lines.

// hello.cpp// A First Program in C++#include <iostream>using namespace std;int main(){

cout << "Hello. My name is Big Bird.\n";system(“pause”);

return 0; //indicates that the program ended successfully}

4. Save the file by selecting File | Save as , and name the file (something like a1.cpp).

5. Select Execute | Compile and Run (or press F9).

You should get an output window like this:

 6. To print the output,    a. Right-click in top bar of output window and choose Select All.

document.doc 6 of 37

Page 7: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

   b. Then right-click again and click Copy.    c. Go back into the editor, select File | New | Source File.    d. In the new window, right-click and select Paste.    e. Then use File | Print to print this window.

7. Go to the source file window and select File | Print to print the source file.

8. Click the X in the top right corner to exit the program.

You have just written (OK, typed) and run your first C++ program! (Whew!)

document.doc 7 of 37

Page 8: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Some Parts of the Program

// hello.cpp// A First Program in C++#include <iostream>using namespace std;int main(){

cout << "Hello. My name is Big Bird.\n";system(“pause”);

return 0; //indicates that the program ended successfully}

(1) comments - At the beginning of each program is a comment, a short description of the problem to be solved. The comment explains the program. The comment is not strictly necessary because a program without it is technically correct. But comments are considered the single most important part of good programming style.

Note that each line of the comment begins with //. Once the symbols // are seen by the C++ compiler, everything to the right is ignored.

(also can have comments that look like this /* */ (if forget last ones what do you think happens?)

(2) Preprocessor directive - Tells the pre-processor to include in the program the contents of the I/O stream header file called iostream.h. This allows us to use standard stream input and output objects like cout (displays to the screen).Any line in a program that starts with # is an instruction to the compiler, not an actual statement in the C++ language. The line containing #include tells the compiler to allow our program to perform standard input and output operations. Because these operations are so basic, this line of code will appear in all the programs we write.

The #include directive tells the compiler that we will be using parts of the standard function library. A function is a building block of a program; typically each function performs one particular task. Information about these functions is contained in a series of header files. In our case, we want the header file called iostream to be included in our program; iostream is short for input/output stream.

document.doc 8 of 37

Page 9: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

C++ divides names into namespaces. Using namespace std is called a using directive. This using directive says that the program is using the std (“standard”) namespace. The names you use will have the meaning defined for them in the std namespace. The line "using namespace std;" allows us to use certain shortcuts, for example to shorten the name of the header file from iostream.h to the simpler iostream. (It also allows the use of string instead of having to say std::string).

(3) int main( ) – main program header - The third line after the comment, int main(), is called the main program header. Every C++ program has at least one function, called main. Program execution begins with the first statement in main. The word int says that this program will return an integer (more about this below), and the empty set of parentheses indicates that the main function will not be sent any information from the outside.

(4) { brackets denote the body of the function }

(5) ; statement terminatorEvery C++ statement must end with a semicolon.

(6) << stream insertion operatorExpression to the right of the operator is inserted (sent) to the cout object (the display screen).

(7) \n newline escape sequence The backslash is an escape character. The character following it takes on a different meaning. eg, \t - tab \a - alert; ring bell

\\ - prints a backslash \” - prints a double quotation mark

(8) return - exits from the functionIn this case control over execution is transferred back to the operating system.

document.doc 9 of 37

Page 10: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Stored Data

Int n;

Variable – a name for a physical location within the computer that can hold one value at a time. (As the name implies, a variable can change its value (e.g. from 4 to 5).

Variables must be declared as a certain type, e.g., int, float, char, … This declaration may appear anywhere in the program before the variable is first used. The declaration creates the object.

Literals - Values, such as a number or text string, that are written literally as part of program code. The opposite of a literal is a variable.

Mnemonic names are useful – like if the variable n is a number from 4 to 9, you can call it number. Or if it’s to hold sum, you can call it sum.

int n;

Semicolon terminates every C++ statement.

The name of the object is n, the type [or class] is int. The object does not yet have a value.

n = 66; //now it has a value

= n is assigned the value 66. (different than mathematical equal sign). or

int n=66; //declaration can be anywhere in the program

(can have more than one variable on the same line int i, j;)

Names (identifiers) - Names should be meaningful to help document your program.

may use letters, digits, underscores. No spaces. may not begin with a digit may be any length but better if less than 31 characters long. C++ is case sensitive; upper and lower case letters are different.

document.doc 10 of 37

Page 11: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

no reserved words (e.g., const, void, int, …). Avoid using names beginning with _ (underscore) or __ (double

underscore). The C++ compiler uses names like that for special purposes.

varname = expr;

price = cost + 3;

If price is initially 7 and cost is 5 what is price after this statement? 8

In C++, double is the primary data type for real numbers. This data type permits decimal places; in addition, it can represent numbers that are extremely large or small. C++ relies on the individual compiler and its implementation on a specific machine to determine the limits of data types. The range of numbers that can be represented by data type int is about five billion; type long int (usually abbreviated as long) has an even larger range of integers.

A variable with data type double can store a much wider range of values and includes numbers with many decimal places. The exact range varies from compiler to compiler, but almost all allow numbers like positive or negative values ranging from 1.0 × 10-30 or 1.0 × 1030, which are infinitesimal and enormous.

C++ has another data type, float, which can also hold floating point numbers but in a smaller range. Although our numbers fit comfortably into variables of type float, we’ll use the larger type double as is commonly done in C++.

Division:

Division in arithmetic is normally --a -- or a ÷ b, but in C++, division is indicated by a b

slash (/). More precisely, a/b means a divided by b. Here are some examples:

• If a is 10 and b is 5, then a/b is 2.

• If a is 11 and b is 4, then a/b is 2 (the fractional part of the answer is lost).

document.doc 11 of 37

Page 12: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

• If a is 10, then a/4. is 2.5 (in this case, the entire answer is kept).

• If a is 4, then 10.0/a is 2.5 (the entire answer is kept).

• If dist is 3.6 and hours is 2.4 then dist/hours is 1.5.

In these examples, the result of division, called the quotient, is sometimes an integer and sometimes not. If either (or both) operand is not an integer (e.g., 10.6/2.3, 10.6/2, or even 10/2.0), the division will work as it does in arithmetic, and the quotient will have decimal places. However, if one integer is divided by another, C++ uses integer division to find the quotient. This value is always an integer since any fractional part of the quotient is chopped off.

Because the fractional part of the answer is lost in integer division, C++ has a modulus or remainder operator, denoted by %, that will give the remainder when one integer is divided by another. For example, if c is 10 and d is 6, then c % d is 4. As another example, 26 % 5 is 1. Also 5 % 6 is 5. In general, x % y gives the remainder when x is divided by y. (The calculations can be tricky if one or both of the values is negative. See Exercise 11 for more details.) Of course, for both of these operations (/ and %), it is understood that the second operand cannot be 0 to avoid the obvious problem of dividing by 0.

A simple C++ programThis program:// Calculates the mean of three numbers.

#include <iostream>using namespace std; //need this to drop .hint main(){

cout << "First Arithmetic Program" << endl; cout << (12+5+10)/3 << endl;

system("pause"); return 0;}

produces this output:

document.doc 12 of 37

Page 13: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

First Arithmetic Program by Big Bird.

9Press any key to continue . . .

(6) << stream insertion operatorExpression to the right of the operator is inserted (sent) to the screen.

Now, let’s try using a variable to store the mean before printing it.

// This program calculates the mean of three numbers.// Big Bird learns about variables.

#include <iostream> using namespace std;int main(){

double mean;cout << "Second Arithmetic Program by Big Bird.\

n\n"; mean = (12+5+10)/3; cout << mean << endl;

system(“pause”); return 0;}

Output:

document.doc 13 of 37

Page 14: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Try a different set of three numbers. Edit the program and run it again.

// calculates the mean of three numbers.// Big Bird tries new data.#include <iostream>using namespace std;int main(){

double mean;cout << "Third Arithmetic Program by Big Bird.\

n\n"; mean = (11+5+10)/3; cout << mean <<endl;

system(“pause”); return 0;}

Third Arithmetic Program by Big Bird.

8Press any key to continue . . .

OOPS!! What happened? [syntax (compile-time) error vs. run-time error vs. logic (run-time) error]

// calculates the mean of three numbers.// Big Bird learns that expressions have a type.

#include <iostream>using namespace std;int main(){

double mean;cout << "Fourth Arithmetic Program by Big Bird.\

n\n"; mean = (11+5+10)/3.0; cout << mean; return 0;

document.doc 14 of 37

Page 15: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

} //end main

Output [that’s better!]:

Third Arithmetic Program by Big Bird.

8.66667Press any key to continue . . .

document.doc 15 of 37

Page 16: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

(C++ Program Phases: …in the C++ programming environment

Edit - Text editor window. Save with .cpp extension

Preprocess - e.g., text replacement, including other library files with the file to be compiled

Compile - to object code

Link - links the object code with the code for the standard library functions referred to in the program. This produces an executable image (with no missing pieces). During Build process

Load - program is placed in memory

Execute - one instruction at a time)

Debugging

You’ve done a program – compiled…

A bug is an error in a program.Debugging is the process of finding and removing errors from a program.

(why called a bug?)1945 - Grace Murray Hopper, working on the Mark II computer, a computer failure was traced to a moth that had become wedged between relay contacts. She taped the moth into the logbook – that was the first case of a bug being found.) (trick – grasshopper)

There are various types of errors that a program might have: compilation, execution, and logic errors.

I Compilation Errors: Errors caught by the compiler while it is translating your program into machine language before running it. Compilation errors caused by mistakes in the syntax of a statement are called syntax errors.

Examples:

a = (b + 1 / 3; // missing parenthesis)x + 3 = 5; (expression on the left of an assignment statement)x = 5 // missing semicolon(for spelled fir)//fir(i=1; i< 5; i++) (misspelled)

document.doc 16 of 37

Page 17: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Linker Errors – errors discovered in the second phase. Phase is handled by the linker – the program that connects your program with the standard libraries. If you use a library function, the compiler looks for it in the standard library during the link phase of copilation. If it doesn’t find the function (either it’s misspelled or doesn’t exist), error message.

Ex: Cuot << num; //misspelled

II Execution Errors or run-time errors: Not caught by the compiler. Detected once the program is running. Ex. suppose that your program attempts to divide by a variable whose value is zero. The compiler will not object to the expression, but the computer will not be able to execute it. Your program will normally stop at the error and display and error message.

Execution errors are more serious than compiler errors and can cause your machine to hang or not give off error messages.

III Logic Errors

Hardest to catch. Each statement may be valid in C++ and acceptable to the compiler. The program may run without causing any execution error, but the answer may be wrong. Ex. initializing a variable to 1 instead of 0, multiplying by 2 instead of 3, or using an incorrect formula. The mistake may be hard to find since it won’t generate an error. You have to catch this kind of error by testing the program on all possible sets of data.

Also, many statements that look like compilation errors are actually valid c++ statements and the compiler won’t think it’s an error: Ex. x = = x+3;

Even if you meant to use the assignment operator.

Another example is previous program / 3.

document.doc 17 of 37

Page 18: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Arithmetic Operators

Addition + Subtraction Multiplication * Division / (is integer division if operators are integers) Modulus % (remainder)

e.g., if the value of

is to be assigned to variable x, it is coded:

x = b + c - d * e / f;

Parentheses may be used. These are evaluated first. e.g., x = (b + c - d)* e / f; is evaluated as:

order of operations( )* / %+ -left to right

ex. z= p*r%q+w/x-y; Order of operations?

Z = P * R % Q + W / X - Y ;6 1 2 4 3 5

Operator Precedence

Operator Associativity Type( ) L R parenthesis ++ – – + – ! R L unary operators* ? % L R multiplicative+ – L R additive<< >> L R insertion< <= > >= L R relational

document.doc 18 of 37

Page 19: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

= = != L R equality&& L R and|| L R or?: R L conditional= += –= *= /= %= R L assignment

document.doc 19 of 37

Page 20: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Exercise: For each of the following arithmetic expressions, construct the equivalent C++ expression.

___(a + b) / (c – d)_____________

____(a+b) / (c * c)________________

_____d – (a + b) / (4 * c)_____

______(b*b – 4*a*c) / (2 * a)___________

______a / (b + c / (d – a))_________

document.doc 20 of 37

Page 21: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

A Simple Program Using Stored Data and Arithmetic

// from Schaum's ex 1.26 p. 27// Prints the sum, difference, etc. of given integers.#include <iostream>using namespace std;

int main(){int m = 6, n = 7;cout << "The integers are " << m << " and

" << n << endl;cout << "Their sum is " << (m+n) << endl;cout << "Their difference is " << (m-n) <<

endl;cout << "Their product is " << (m*n) <<

endl;cout << "Their quotient is " << (m/n) <<

endl;cout << "Their remainder is " << (m%n) <<

endl << endl << endl;system(“pause”);return 0;

}

Trace this program.

The integers are 6 and 7Their sum is 13Their difference is -1Their product is 42Their quotient is 0Their remainder is 6

Press any key to continue . . .

document.doc 21 of 37

Page 22: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Assignment

c = c + 3; same as c +=3;The += operation adds the value of the expression of the right to the value of the variable on the left and stores the result in the variable on the left.

In general, <var> = <var> op <exp>; can be written as: <var> op = <exp>;

Examples:c = 4; same as c = c 4;c *= 5; same as c = c *5;c /= 6; same as c = c /6;

Can we reverse the order of the double operator? e.g.: c = 4;No. This simply is the same as the assignment c = 4;

For loops

Here is an example of a simple for loop that will print the numbers from 1 to 5.

int i;

for (i = 1; i <= 5; i = i + 1) // header of the loop cout << i << endl; // body of the loop

Note that the header does not end in a semicolon because by itself it is not a complete C++ statement, just as the header of a main program is not one. The header is always followed by something called the body of the loop. The header together with the body is a complete C++ statement. This simple for loop starts by giving an initial value to a variable (in our example, i), which we will call the index or control variable. The process of giving a variable an initial value is called initialization, and we say that i is initialized to 1. The for loop tells the computer to repeat the body of the loop, which in our example contains the single cout instruction, for several values of i. In this case, it will output the value i for i = 1, 2, 3, 4, and 5.

document.doc 22 of 37

Page 23: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

The for loop header specifies three things, separated by semicolons: what initial value to use, what test determines whether or not the loop should continue, and how the loop control variable should change (in this case, increment) each time through the body of the loop.

initial value increment for loop header: for (i = 1; i <= 5; i = i + 1) test whether to continue the loop

The for loop header is followed by the body of the loop. We are allowed to specify one statement that will be executed each time through the loop. In this case, that one statement is cout. Each time through the body of the loop, the current value of i is sent to cout. Then the new value of i, which is obtained by adding 1 to the previous value of i, is used to test the condition controlling the loop. CAUTION:Even though the increment step (i = i + 1) is contained in the header, it is executed after the body of the loop on each pass.

Tracing the for Loop

Now let's go step by step through the for loop. Going step by step is called tracing or hand simulating a program and is an extremely important programming tool.

PROGRAM TRACE:

• The variable i starts at 1, which is compared to the final value of 5. Since 1 is less than or equal to 5, the program enters the body of the loop and sends the value of i to cout, printing 1. This completes the first pass through the for loop.

• Then we increment i by 1 to 2 and compare this new value to 5. Since 2 is less than or equal to 5, we execute the body of the loop. This time the program prints 2 on a new line. This completes the second pass.

document.doc 23 of 37

Page 24: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

• Then i increases to 3, which is less than or equal to the limiting value of the control variable (5), so we print 3.

• Similarly, i increases to 4, and we print 4.

• Then i increases to 5, which is also allowed since we test whether the current value is less than or equal to the final value. The program prints 5.

• Then i increases to 6. At this point, the condition i <= 5 is no longer true. Therefore, we do not enter the body of the loop when i has the value 6. Instead, the for loop is completed, and we continue with the next statement following the loop. In our example, since the body of the loop consists of a statement to print the value of i, the entire for loop prints the values 1, 2, 3, 4, and 5, each on a separate line.

A for Loop Using a Compound Statement

Let's look at a slightly more complicated example, which is very close to what we want to do in Problem 1. In this example, we will do two things inside the body of the for loop.

After the header in a for loop, we are allowed to execute only a single statement. However, a pair of braces is used in C++ whenever we want to execute a series of statements where normally just one is allowed. This entire series, called a compound statement, can then be treated as a single statement.

Example:A loop to compute the expression i * i, store it in a variable called sq,

then print both i and sq.

int i,sq;

for (i = 1; i <= 5; i = i + 1) { sq = i * i; cout << i << sq << endl; }

document.doc 24 of 37

Page 25: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Shorthand for Increments: ++ and --

Because increment statements are so common, C++ has a shortcut form that is almost always used. In the line below, the statement on the right is an abbreviation for the statement on the left.

i = i + 1; can be replaced by i++;

for (number = 4; number <= 9; number++)

In the same way, subtracting one from a variable can be abbreviated by using the decrement operator --. For example, these two statements are equivalent:

number = number - 1; and number--;

Once again, here is an example using a for loop header:

for (number = 9; number >= 4; number--)

Finally, the increment and decrement operators can also appear to the left of the variable name. In the case of a simple assignment statement (e.g., as part of a for loop header), these three statements have the same meaning:

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

However, if the increment or decrement operator is used as part of a larger expression, there can be differences in meaning.

Int I = 4;Cout << i++;Cout <<i;

Output: 4 5

Int i=4;Cout << ++i;Count << i;

document.doc 25 of 37

Page 26: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Output 5 5

Unary Increment/Decrement Operators

a++; same as a = a + 1; same as ++a;a; same as a = a 1; same as a;

a++ postincrement++a preincrementa postdecrementa predecrement

Example:

int c;c = 5;cout << c << endl; //prints 5cout << c++ << endl; //prints 5 (then increments)cout << c << endl << endl; //prints 6c = 5;cout << c << endl; //prints 5cout << ++c << endl; //prints 6 (after incrementing)cout << c << endl; //prints 6

Why was C++ named C++?

C++ was derived from C, so this is a cute pun since it’s an operation in these languages. C was called C because it was derived from the B language. B was derived from the language BCPL.

(why was java called java (c++++, oak, coffee) – programmers have strange sense of humor)

(SNOBOL, 1963, StriNg Oriented SymBOlic Language – originally called SEXI – String EXpression Interpreter – a little awkward as a programming language name).

If Statements

document.doc 26 of 37

Page 27: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

In pseudocode (structured English) we might express a decision as:

If student’s grade is greater than or equal to 60 Print “Passed”

In C++ this would be coded as:

if (grade >= 60)cout << “Passed”;

Syntax for if statement:if <boolean expression > <statement1> ;

A boolean expression represents a condition that is either true or false. It is formed using operands (constants, variables) and operators (arithmetic operators, relational operators, logical operators). • If the condition is true, we execute the statement that follows [in this case, cout << "You Passed!" << endl, and continue processing.

result = 75; if (result >= 60) cout << "You Passed!"; cout << endl;

• If the condition is false, we simply skip that statement and "fall through" to the next instruction.

result = 45; if (result >= 60) cout << "You Passed!"; cout << endl;

In the example above, if result is greater than or equal to 0, we print the word "Admit," but if result is less than 0, we don't. Instead, we proceed to the next statement, which sends the cursor to a new line in all cases.

if (cond) // no semicolon here stmt-1; // end of if statementstmt-2; // next statement

document.doc 27 of 37

Page 28: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Arithmetic Relational Logical+ - < less than > greater than || or* / % == equal to

!= not equal to&& and

arithmetic functions <= less than or equal to>= greater than or equal to

! not

Ex. if ((x > 0) && (a == b)) …

Maybe this one:

Operator Precedence

Operator Associativity Type( ) L R parenthesis ++ – – + – ! R L unary operators* ? % L R multiplicative+ – L R additive<< >> L R insertion< <= > >= L R relational= = != L R equality&& L R and|| L R or?: R L conditional= += –= *= /= %= R L assignment

Precedence of Arithmetic, Assignment, and Relational Operators---------------------------------------------------------------------------------------- Associativity

highest precedence - (unary) + (unary) ++ -- right to left (done first) * / % left to right + - left to right

< <= > >= left to right == != left to right

lowest precedence = += -= *= /= %= right to left (done last) -------------------------------------------------------------------------------------

document.doc 28 of 37

Page 29: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

for(num=1;num<10;num++)sum = sum + num;

same asfor(num=1;num<10;num++)

sum += num;

(go through multiply, divide, etc)

Standard Library of Functions (math.h)

In addition to the five standard arithmetic operations (+, -, *, /, and %), C++ offers simple functions to perform other mathematical operations. These functions save us a lot of calculation; instead, the computer does most of the work. For example, sometimes we need the square root of a number. C++ has a function called sqrt() that automatically finds the square root.

double w,root; w = 12; root = sqrt(w + 7); The expression sqrt(w + 7) finds the square root of w + 7. Since w has the value 12, the sqrt() function finds the square root of 19 (which is 4.36) and assigns it to root.

The function sqrt() is called a library function because its instructions are stored in a library. (Note: In C++, when referring to the name of a function, it is customary to use parentheses after the name; this distinguishes the name of a function from other types of identifiers.) The collection of these functions is called the standard library of functions or the C++ standard library.

The expression which invokes a function from the standard library is known as the call to the function or a function call. Typically, the function call specifies two things: the name of the function and the value or values on which the function should operate.

document.doc 29 of 37

Page 30: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

root = sqrt(w+7); function value on which name sqrt() should operate

A call to a library function can be placed on the right-hand side of an assignment statement, in a cout expression, or anywhere that an expression can occur. For example, here are some C++ statements that use library functions (we will explain ceil() and floor() in a moment):

a = sqrt(b); cout << ceil(5.5); z = x + floor(w);

#include<iostream>#include<math.h>using namespace std;int main(){ cout << sqrt(25) << endl; cout << ceil(5.5) << endl; cout << floor(3.6) << endl; system("pause");}output: 563

In addition to sqrt(), there are many other library functions. A useful one is abs(). The expression abs(x) finds the absolute value of the integer x, which in mathematics is written |x|. A call to abs() always returns a positive or 0 integer answer.

Talk about HW:

Math.h vs. cmath (sqrt)

#include <cmath>

at the beginning of the program. If you use math.h, which is a C library, you will need to specify #include <math.h> because C header files require .h. Using .h is not required for C++ header files, but it is for C header files.

document.doc 30 of 37

Page 31: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Setw

Manipulator – function that is called in a nontraditional way. Manipulators area placed after the insertion operator.Endl is a manipulator function. manipulator may or may not have arguments. We have others ex: setw.

Endl – means end of line. It does the same thing as appending the endline character ‘\n’ to the string itself.

Setw means set the output field width to 4 columns for the next output.

Cout << “Start” << setw(4) << 10 << setw(4) << 20 << setw(6) << 30;

Start 10 20 30

(2 spaces before the 10, two before the 20, and 4 before the 30).

document.doc 31 of 37

Page 32: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Types

Integer TypesIntegers stored in either 16 or 32 bitsInteger Types – signed and unsigned

Signed Integer – leftmost signbit is 0 if the number is positive or 0, and 1 if it’s negative.

Largest 16 bit integer is 32,767 (2 to 15 power – 1). 32-bit is 2,147,483,647 (2 to 31 power – 1).

Unsigned Integer – no sign bit. 16 bit= 65,535(2 to 16 power – 1)32 bit = 4,294,967,295(2 to 32 power – 1) default signed in C. we declare unsigned if want no sign bit. Useful for systems programming and low-level, machine-dependent applications. We’ll discuss later – (when dealing with long numbers – strings – converting)Avoid unsigned for now

Long integers – A 16-bit integer with its upper limit of 32,767 may be too limited for many applications, C also provides long integers. (2,147,483,647)

Short integer – may need to save space at times by instructing the compiler to store a number in less space than normal.

Declarations

Constant declarations:Used to associate meaningful names with constants -- items that will never change throughout execution of the program.

const float PI=3.14159;

Variable declarations:

document.doc 32 of 37

Page 33: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Used to associate identifiers of a given type with memory cells used to store values of this type. - the values stored in the data cells are changeable.

char letter;char letter1, letter2;float x, y;

Data Type char

Char stands for character. A variable of this data type can hold any one character (e.g., 'a' or ' ' or '?'). A character is essentially anything that can be typed--a number, letter, space, period, or symbol. In addition, special characters like the tab character '\t' (used earlier in this chapter) and newline character '\n' (which can be used in place of endl) are values of type char.

( some computers (DOS PCs) the int set of values consists of all integers in the range –32,768 to 32,767.

There are nine int types:short int unsigned short int charint unsigned int signed charlong int unsigned long int unsigned char

The difference among these 9 types is the range of values they allow. These ranges may depend somewhat on the computer system.

short is the same as short int)

char type uses 8 bits to store a single character. Is actually numeric in that it stores the ASCII code value of the character. Character input is automatically converted; on output the value is converted to char first.

char

…char c = 64;cout << c << “ “; //prints ‘@’ c = c + 1; //increments c to 65cout << c << “ “; //prints ‘A’ c = c + 1; //increments c to 66cout << c << “ “; //prints ‘B’ c = c + 1; //increments c to 67cout << c << “ “; //prints ‘C’ …

document.doc 33 of 37

Page 34: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

EXAMPLE 2-17:

char letter;

letter = 'a'; if (letter != 'b') cout << "letter has the value " << letter << '\n';

Since letter is not equal to 'b', this example prints the following:

letter has the value a

Data type char is actually a subset of data type int. Each char value has a number associated with it, called its ASCII value; the ASCII values for characters range from 0 to 255. We could change the declaration in Example 2-17 to the following without altering the code:

int letter;

For a while, we will use characters only as part of strings to be printed, since a variable of type char by itself is not very useful (it can hold only one character).

convert to uppercase:

if(‘a’<=ch && ch <=’z’)ch=ch – ‘a’ +’A’;

a=97A=65

Real number typesfloat double long double

On most systems, double uses twice as many bytes as float. In general, float uses 4 bytes, double uses 8 bytes, and long double uses 8, 10, 12, or 16 bytes.

// Prints the amount of space each of the 12 fundamental types uses.

#include <iostream>

document.doc 34 of 37

Page 35: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

using namespace std;int main(){

cout << "Number of bytes used:\n "; cout << "\t char: " << sizeof(char) << endl; cout << "\t short: " << sizeof(short) << endl; cout << "\t int: " << sizeof(int) << endl; cout << "\t long: " << sizeof(long) << endl; cout << "\t unsigned char: " << sizeof(unsigned char) << endl; cout << "\t unsigned short: " << sizeof(unsigned short) << endl; cout << "\t unsigned int: " << sizeof(unsigned int) << endl; cout << "\t unsigned long: " << sizeof(unsigned long) << endl; cout << "\t signed char: " << sizeof(signed char) << endl; cout << "\t float: " << sizeof(float) << endl; cout << "\t double: " << sizeof(double) << endl; cout << "\t long double: " << sizeof(long double) << endl;system(“pause”);return 0;}Output:

Number of bytes used: char: 1 short: 2 int: 4 long: 4 unsigned char: 1 unsigned short: 2 unsigned int: 4 unsigned long: 4 signed char: 1 float: 4 double: 8 long double: 12Press any key to continue . . .

document.doc 35 of 37

Page 36: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

Casting

Dividing two integers will give you an int result, you can change one to be a double to give you a double result.

If both of the operands in a division are variables:

int total_candy, number_of_people;double candy_per_person;#program sets total_candy to 9 and number_of_people to 2candy_per_person = total_candy/number_of_people;

Unless you convert the value in one of the variables total_candy or number_of_people to a value of type double, the result of the division will be 4 and not 4.5 as it should be.

The fact that the variable candy_per_person is of type double doesn’t help. If one was a constant, you could add a decimal point and a zero to convert the constant to double, bu there both are variables.

In c++ we could convert:

double(9)The type double can be used as if it were a predefined function that converts a value of some other type, such as 9, to a value of type double, 9.0. (it’s a kind of predefined function) It’s called type casting.

Double answer;Answer = double(9)/2;

Rewrite earlier example:

int total_candy, number_of_people;double candy_per_person;#program sets total_candy to 9 and number_of_people to 2candy_per_person = double(total_candy)/number_of_people;

Do the typecasting before you do the division. If you wait until after the division is completed then the digits after the decimal point are already lost.

document.doc 36 of 37

Page 37: Running your first C++ program in Borland C++radler/notesrf/cis1.5/introductory con…  · Web viewBecause these operations are so basic, this line of code will appear in all the

If you use this the value will be 4.0 not 4.5:

candy_per_person = double(total_candy/number_of_people); // WRONG!

(C does (double)total_candy/number_of_people – this is the same idea – it does it on the total_candy not the whole thing. So that works too, but the other way is C++)

document.doc 37 of 37