Copyright © 2012 Pearson Education, Inc. Chapter 2 Simple C++ Programs.

Post on 29-Dec-2015

213 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

Transcript

Copyright © 2012 Pearson Education, Inc.

Chapter 2

Simple C++ Programs

Introduction to C++

Dr. Ahmed Telba

King Saud University

College of Engineering

Electrical Engineering Department

Table : Valid Variable Names

Statements and Expressions

The increment (++) or decrement (—)

operator• When using the increment (++) or decrement (—) operator, it is

necessary to be careful of where you put it. If you put the operator before the variable, then that operation will take place before any other operations in the expression. Some examples follow.

• int answer,• num; num = 5;• Now using the expression,• answer = num++;• the value of num will first be put in answer, THEN incremented.• In other words, the value of answer will be set to 5, and then the

value of num will be incremented. If you want num to be incremented BEFORE you assign the value to answer then you must put the increment operator first, as shown in the following example.

• answer = ++num;

Basic Structure of a C++ program

int main()

{

return 0;

}

• Or

• void main()

• use no need return 0

#include <iostream>int main()

{ int j; j = 5; j++; return 0; }

First program in C++#include <iostream>using namespace std;

int main(){ // Print hello world on the screen cout << "Hello World\n " ; system("pause"); // only if using Dev C++

compiler

return 0;}

Haw to avoid return 0 #include <iostream>using namespace std;

main(){ // Print hello world on the screen cout << "Hello World\n " ; system("pause"); //return 0;}

Program 2#include <iostream>using namespace std;

int main(){ // the following code demo’s various escape keys cout << "\" Hello World \" \n"; cout << "C++ is COOL! \n \a"; return 0;}

#include <iostream>using namespace std;

int main(){

cout << "As you can see these \" escape keys \" \n";

cout << "are quite \'useful \' \a \\ in your code \\ \a \n";

return 0;}

#include <iostream>using namespace std;

int main(){

cout << "You have previously used the \\n key to get a new line \n";

cout << "However you can also use the endl command"<<endl;

system("pause"); return 0;}

#include <iostream>using namespace std;

int main(){ char text[10];

cout << "Please enter a word\n";cin.getline(text,10);cout << text << endl;system("pause");return 0;

}

Example 2.1

#include <iostream>using std::cout; using std::cin;int main(){ // Print hello world on the screen cout << "Hello World"; return 0;}

Example 2.2

#include <iostream>using std::cout; using std::cin;int main(){ cout << "Hello World \n"; return 0;}

Example 2.3#include <iostream>using std::cout; using std::cin;int main(){ // the following code demo's various escape keys cout << "\" Hello World \" \n"; cout << "C++ is COOL! \n \a"; return 0;}

Example 2.4

#include <iostream>using std::cout;int main(){cout << "As you can see these \" escape keys \" \n";cout << "are quite \'useful \' \a \\ in your code \\ \a \n";return 0; }

Copyright © 2012 Pearson Education, Inc.

OutlineObjectives

1. C++ Program Structure

2. Constant and Variables

3. C++ Classes

4. C++ Operators

5. Standard Input and Output

6. Building C++ Solutions with IDEs

7. Basic Functions in C++ Standard Library

8. Problem Solving Applied

9. System Limitations

Copyright © 2012 Pearson Education, Inc.

Objectives

Develop problem-solving solutions inC++ containing:

• Simple arithmetic computations

• Information printed on the screen

• User-supplied Information from keyboard

• Programmer-defined data types

C++ Program Structure

/*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */#include <iostream> // Required for cout, endl.#include <cmath> // Required for sqrt()using namespace std;int main() {// Declare and initialize objects. double x1(1), y1(5), x2(4), y2(7), side1, side2, distance;// Compute sides of a right triangle. side1 = x2 - x1; side2 = y2 - y1; distance = sqrt(side1*side1 + side2*side2);// Print distance. cout << "The distance between the two points is " << distance << endl;// Exit program.return 0;}//--------------------------------------------------------

Copyright © 2012 Pearson Education, Inc.

/*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */#include <iostream> // Required for cout, endl.#include <cmath> // Required for sqrt()using namespace std;int main() {// Declare and initialize objects. double x1(1), y1(5), x2(4), y2(7), side1, side2, distance;// Compute sides of a right triangle. side1 = x2 - x1; side2 = y2 - y1; distance = sqrt(side1*side1 + side2*side2);// Print distance. cout << "The distance between the two points is " << distance << endl;// Exit program.return 0;}//--------------------------------------------------------

Copyright © 2012 Pearson Education, Inc.

Comments:•document the program’s purpose•Help the human reader understand the program•Are ignored by the compiler•// comments to end-of line•/* starts a comment block ending with */

/*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */#include <iostream> // Required for cout, endl.#include <cmath> // Required for sqrt()using namespace std;int main() {// Declare and initialize objects. double x1(1), y1(5), x2(4), y2(7), side1, side2, distance;// Compute sides of a right triangle. side1 = x2 - x1; side2 = y2 - y1; distance = sqrt(side1*side1 + side2*side2);// Print distance. cout << "The distance between the two points is " << distance << endl;// Exit program.return 0;}//--------------------------------------------------------

Copyright © 2012 Pearson Education, Inc.

Preprocessor Directives:•Give instructions to the preprocessor before the program is compiled.•Begin with # #include directives ‘add’ or ‘insert’ the named files (and the functionality defined in the files)into the program

/*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */#include <iostream> // Required for cout, endl.#include <cmath> // Required for sqrt()using namespace std;int main() {// Declare and initialize objects. double x1(1), y1(5), x2(4), y2(7), side1, side2, distance;// Compute sides of a right triangle. side1 = x2 - x1; side2 = y2 - y1; distance = sqrt(side1*side1 + side2*side2);// Print distance. cout << "The distance between the two points is " << distance << endl;// Exit program.return 0;}//--------------------------------------------------------

Copyright © 2012 Pearson Education, Inc.

‘using’ Directives:•Tell the compiler to use the library names declared in the namespace.The ‘std’, or standard namespace contains C++ language-defined components.

/*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */#include <iostream> // Required for cout, endl.#include <cmath> // Required for sqrt()using namespace std;int main() {// Declare and initialize objects. double x1(1), y1(5), x2(4), y2(7), side1, side2, distance;// Compute sides of a right triangle. side1 = x2 - x1; side2 = y2 - y1; distance = sqrt(side1*side1 + side2*side2);// Print distance. cout << "The distance between the two points is " << distance << endl;// Exit program.return 0;}//--------------------------------------------------------

Copyright © 2012 Pearson Education, Inc.

Main function header:•Defines the starting point (i.e. entry point) for a C++ program•The keyword ‘int’ indicates that the function will return an integer value to the system when the function completes.

/*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */#include <iostream> // Required for cout, endl.#include <cmath> // Required for sqrt()using namespace std;int main() {// Declare and initialize objects. double x1(1), y1(5), x2(4), y2(7), side1, side2, distance;// Compute sides of a right triangle. side1 = x2 - x1; side2 = y2 - y1; distance = sqrt(side1*side1 + side2*side2);// Print distance. cout << "The distance between the two points is " << distance << endl;// Exit program.return 0;}//--------------------------------------------------------

Copyright © 2012 Pearson Education, Inc.

Code blocks:•are zero or more C++ declarations or statements enclosed by curly brackets { }The code that defines what a function does (in this case, the main function of the program) is often defined in a code block following the header.

/*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */#include <iostream> // Required for cout, endl.#include <cmath> // Required for sqrt()using namespace std;int main() {// Declare and initialize objects. double x1(1), y1(5), x2(4), y2(7), side1, side2, distance;// Compute sides of a right triangle. side1 = x2 - x1; side2 = y2 - y1; distance = sqrt(side1*side1 + side2*side2);// Print distance. cout << "The distance between the two points is " << distance << endl;// Exit program.return 0;}//--------------------------------------------------------

Copyright © 2012 Pearson Education, Inc.

Declarations:•Define identifiers (e.g. variables and objects) and allocate memory.•May also provide initial values for variables.•Must be made before actions can be performed on variables / objects.

/*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */#include <iostream> // Required for cout, endl.#include <cmath> // Required for sqrt()using namespace std;int main() {// Declare and initialize objects. double x1(1), y1(5), x2(4), y2(7), side1, side2, distance;// Compute sides of a right triangle. side1 = x2 - x1; side2 = y2 - y1; distance = sqrt(side1*side1 + side2*side2);// Print distance. cout << "The distance between the two points is " << distance << endl;// Exit program.return 0;}//--------------------------------------------------------

Copyright © 2012 Pearson Education, Inc.

Statements :•specify the operations to be performed.

Constantsand

Variables

Copyright © 2012 Pearson Education, Inc.

Constants and Variables• Constants and variables represent memory locations that

we reference in our program solutions.• Constants are objects that store specific data that can not be

modified.– 10 is an integer constant– 4.5 is a floating point constant– "The distance between the two points is" is a string

constant

– 'a' is a character constant

• Variables are named memory locations that store values that can be modified. – double x1(1.0), x2(4.5), side1;– side1 = x2 - x1;– x1, x2 and side1 are examples of variables that can be modified.

Copyright © 2012 Pearson Education, Inc.

Initial Values

• C++ does not provide initial valuesfor variables.– Thus using the value of a variable before it is

initialized may result in ‘garbage’.

Copyright © 2012 Pearson Education, Inc.

Memory Snapshots

• Memory ‘snapshots’ are diagrams that show the types and contents of variables at a particular point in time.

Copyright © 2012 Pearson Education, Inc.

Valid C++ Identifiers

• Must begin with an alphabeticcharacter or the underscore character ‘_’

• Alphabetic characters may be either upper or lower case.– C++ is CASE SENSITIVE, so ‘a’ != ‘A’, etc…

• May contain digits, but not in as the first character.

• May be of any length, but the first 31 characters must be unique.

• May NOT be C++ keywords.Copyright © 2012 Pearson Education, Inc.

C++ Keywords

Copyright © 2012 Pearson Education, Inc.

C++ Identifiers

• Should be carefully chosen to reflectthe contents of the object.– The name should also reflect the units of

measurements when applicable.

• Must be declared (and therefore typed) before they may be used.– C++ is a strongly typed programming

language.

Copyright © 2012 Pearson Education, Inc.

Common C++ Data Types

• Keyword Example of a constant– bool true– char '5'– int 25– double 25.0– string "hello" //#include<string>

Copyright © 2012 Pearson Education, Inc.

Declarations• A type declaration statement defines

new identifiers and allocates memory.• An initial value may be assigned to a memory

location at the time an identifier is defined.

Copyright © 2012 Pearson Education, Inc.

Syntax[modifier] type specifier identifier [= initial value];[modifier] type specifier identifier[(initial value)];

Examplesdouble x1, y1(0);int counter=0;const int MIN_SIZE=0;bool error(false);char comma(',');

Symbolic Constants

• A symbolic constant is defined in a declaration statement using the modifier const.

• A symbolic constant allocates memory for an object that can not be modified during execution of the program. Any attempt to modify a constant will be flagged as a syntax error by the compiler.

• A symbolic constant must be initialized in the declaration statement.

Copyright © 2012 Pearson Education, Inc.

C++ Classes

Copyright © 2012 Pearson Education, Inc.

Class Declarations• Specify a programmer-defined type/object.

• Begin with keyword ‘class’ followed by the name (i.e. identifier) of the type.– Class definition is made in a code block.– Class members may include data (attributes)

and methods (functions).– Visibilities of public, protected, and private

are used to control access to class members– A semicolon must follow the closing bracket };

Copyright © 2012 Pearson Education, Inc.

Class Methods• Define the operations that can be

performed on class objects.– A constructor is a special method that is executed

when objects of the class type are created (instantiated).

– Constructors must have the same name as the class.– A class may define multiple constructors to allow

greater flexibility in creating objects.• The default constructor is the one that has no parameters.• Parameterized constructors provide initial values of data

members.

Copyright © 2012 Pearson Education, Inc.

Class Definitions

• Often declared in two parts:– The class declaration is typically written in a

file named ‘className.h’• Defines the class including data members and the

headers of the class methods.

– The implementation of class methods is typically written in a file named ‘className.cpp’

• #include “className.h”• Provides implementations for all class methods.

Copyright © 2012 Pearson Education, Inc.

Class Syntax

Copyright © 2012 Pearson Education, Inc.

Using a Class

• Once a class is defined, you may usethe class as a type specifier.– You must include the class definition (i.e. header

file)

Copyright © 2012 Pearson Education, Inc.

C++ Operators

Copyright © 2012 Pearson Education, Inc.

Assignment Operator

• The assignment operator (=) is usedin C++ to assign a value to a memory location.

• The assignment statement:x1 = 1.0;

– assigns the value 1.0 to the variable x1.– Thus, the value 1.0 is stored in the memory

location associated with the identifier x1.(Note: x1 must have been previously declared.)

Copyright © 2012 Pearson Education, Inc.

Order of Types

• Because different types are differentrepresentations, frequently we need to convert between types.– Sometimes these conversions may

loose information.– Conversion from lower types to

higher types results in no loss of information.

– Conversion from higher types to lower types may loose information.

Copyright © 2012 Pearson Education, Inc.

High:

Low:

long doubledoublefloatlong integerintegershort integer

Assignment Statements

Assignment operators must not be confused with equality.

Copyright © 2012 Pearson Education, Inc.

Arithmetic Expressions

• Expressions appearing in assignmentstatements for numeric variables may be simple literals (e.g. x1 = 10.4;), reading the value stored in a variable (e.g. x2= x1;), or be more complex expressions involving the evaluation of one or more operators (e.g. x1 = -3.4*x2 + 10.4).

Copyright © 2012 Pearson Education, Inc.

Arithmetic Operators• Addition +• Subtraction -• Multiplication *• Division /• Modulus %

– Modulus returns remainder of division between two integers

– Example

5%2 returns a value of 1

Copyright © 2012 Pearson Education, Inc.

Operator Basics

• The five operators (* / % + -) arebinary operators - operators that require two arguments (i.e. operands).

• C++ also include operators that require only a single argument – unary operators.– For example, a plus or a minus sign

preceding an expression can be unary operators: (e.g. -x2).

Copyright © 2012 Pearson Education, Inc.

Integer Division

• Division between two integers resultsin an integer.

• The result is truncated, not rounded

• Example:The expression 5/3 evaluates to 1

The expression 3/6 evaluates to 0

Copyright © 2012 Pearson Education, Inc.

Mixed Operations

• Binary operations on two values ofsame type yield a value of that type (e.g. dividing two integers results in an integer).

• Binary operations between values of different types is a mixed operation.– Value of the lower type must be converted to

the higher type before performing operation.– Result is of the higher type.

Copyright © 2012 Pearson Education, Inc.

Casting

• The cast operator.– The cast operator is a unary operator that requests

that the value of the operand be cast, or changed, to a new type for the next computation. The type of the operand is not affected.

• Example:int count(10), sum(55);

double average;

average = (double)sum/count;

Copyright © 2012 Pearson Education, Inc.

Memory snapshot:

int count

int sum

double average

10

55

5.5

Overflow and Underflow• Overflow

– answer too large to store Example: using 16 bits for integersresult = 32000 +532;

• Exponent overflow – answer’s exponent is too largeExample: using float, with exponent range –38 to 38result = 3.25e28 * 1.0e15;

• Exponent underflow – answer’s exponent too smallExample: using float, with exponent range –38 to 38result = 3.25e-28 *1.0e-15;

Copyright © 2012 Pearson Education, Inc.

Increment and DecrementOperators

• Increment Operator ++• post increment x++;• pre increment ++x;

• Decrement Operator - -• post decrement x- -;• pre decrement - -x;

• For examples assume k=5 prior to executing the statement.

• m= ++k; // both m and k become 6• n = k- -; // n becomes 5 and k becomes 4

Copyright © 2012 Pearson Education, Inc.

Abbreviated AssignmentOperators

operator example equivalent statement

+= x+=2; x=x+2;

-= x-=2; x=x-2;

*= x*=y; x=x*y;

/= x/=y; x=x/y;

%= x%=y; x=x%y;

Copyright © 2012 Pearson Education, Inc.

Operator Precedence

Copyright © 2012 Pearson Education, Inc.

Precedence Operator Associativity

1 Parenthesis: () Innermost First

2 Unary operators:+ - ++ -- (type)

Right to left

3 Binary operators:* / %

Left to right

4 Binary operators:+ -

Left to right

5 Assignment Operators= += -= *= /= %=

Right to left

Standard Input / Output

Copyright © 2012 Pearson Education, Inc.

Sample Output - cout• cout is an ostream object, defined in the header

file iostream

• cout is defined to stream data to standard output (the display)

• We use the output operator << with cout to output the value of an expression.

General Form:cout << expression << expression;

Note: An expression is a C++ constant, identifier, formula, or function call.

Copyright © 2012 Pearson Education, Inc.

Simple Input - cin

• cin is an istream object definedin the header file iostream

• cin is defined to stream data from standard input (the keyboard)

• We use the input operator >> with cin to assign values to variables

– General Formcin >> identifier >> identifier;

• Note: Data entered from the keyboard must be compatible with the data type of the variable.

Copyright © 2012 Pearson Education, Inc.

Characters and Input

• The input operator >> skips all whitespace characters.

• The get() method gets the next character.• Example:

int x;char ch;cin >> x >> ch;cin >> x;cin.get(ch);

Copyright © 2012 Pearson Education, Inc.

Input stream:45 c39b

Memory Snapshot

x ch

x ch

45 ‘c’

39 ‘\n ’

Manipulators and Methods• endl – places a newline character in the

output buffer and flushes the buffer.• setf() and unsetf()

Copyright © 2012 Pearson Education, Inc.

Flag Meaning

ios::showpoint display the decimal point

ios::fixed fixed decimal notation

ios::scientific scientific notation

Ios::setprecision(n) set the number of significant digits to be printed to the integer value n

Ios::setw(n) set the minimum number of columns for printing thenext value to the integer value n

ios::right right justification

ios::left left justification

Building C++ Solutions with IDEs

Copyright © 2012 Pearson Education, Inc.

Integrated Development Environments (IDEs)

• IDEs are software packages designedto facility the development of software solutions.

• IDEs include:– Code editors– Compiler– Debugger– Testing tools– Many additional helpful tools…

Copyright © 2012 Pearson Education, Inc.

Basic Functions in C++ Standard Library

Copyright © 2012 Pearson Education, Inc.

Basic C++ Math Functions

Copyright © 2012 Pearson Education, Inc.

fabs(x) computes absolute value of x

sqrt(x) computes square root of x, wherex >=0

pow(x,y) computes xy

ceil(x) nearest integer larger than x

floor(x) nearest integer smaller than x

exp(x) computes ex

log(x) computes ln x, where x >0

log10(x) computes log10x, where x>0

Trigonometric Functions

Copyright © 2012 Pearson Education, Inc.

sin(x) sine of x, where x is in radians

cos(x) cosine of x, where x is in radians

tan(x) tangent of x, where x is in radians

asin(x) This function computes the arcsine, or inverse sine, of x, where x must be in the range [−1, 1].

The function returns an angle in radians in the range [−π/2, π/2].

acos(x) This function computes the arccosine, or inverse cosine, of x, where x must be in the range [−1, 1].

The function returns an angle in radians in the range [0, π].

atan(x) This function computes the arctangent, or inverse tangent, of x.

The function returns an angle in radians in the range [−π/2, π/2].

atan2(y,x) This function computes the arctangent or inverse tangent of the value y/x.

The function returns an angle in radians in the range [−π, π].

Common FunctionsDefined in <cctype>

Copyright © 2012 Pearson Education, Inc.

isalpha(ch) Returns true if ch is an upper or lower case letter.

isdigit(ch) Returns true if ch is a decimal digit

isspace(ch) Returns true if ch is a whitespace character.

islower(ch) Returns true if ch is an lower case letter.

isupper(ch) Returns true if ch is an upper case letter.

tolower(ch) Returns the lowercase version of ch if ch is an uppercase character, returns ch otherwise.

toupper(ch) Returns the uppercase version of ch if ch is a lowercase character, returns ch otherwise.

Copyright © 2012 Pearson Education, Inc.

Problem Solving Applied

Copyright © 2012 Pearson Education, Inc.

Copyright © 2012 Pearson Education, Inc.

System Limitations

Copyright © 2012 Pearson Education, Inc.

System Limitations

• C++ standards do not specifylimitations of data types – they are compiler-specific.

• C++ does provide standard methods of accessing the limits of the compiler:– <climits> defines ranges of integer types.– <cfloat> defines ranges of floating-point types.– the sizeof(type) function returns the memory

size of the type, in bytes.Copyright © 2012 Pearson Education, Inc.

top related