Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Copyright © 2012 Pearson Education, Inc. Chapter 2 Simple C++ Programs."— Presentation transcript:

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

2 Introduction to C++ Dr. Ahmed Telba King Saud University College of Engineering Electrical Engineering Department

3

4 Table : Valid Variable Names

5 Statements and Expressions

6

7 The increment (++) or decrement (—) opera tor 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;

8 Basic Structure of a C++ program int main() { return 0; } Or void main() use no need return 0

9 #include int main() { int j; j = 5; j++; return 0; }

10 First program in C++ #include 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; }

11

12 Haw to avoid return 0 #include using namespace std; main() { // Print hello world on the screen cout << "Hello World\n " ; system("pause"); //return 0; }

13 Program 2 #include 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; }

14

15 #include 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; }

16

17 #include 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; }

18

19 #include 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; }

20

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

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

23

24 Example 2.3 #include 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; }

25 Example 2.4 #include 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; }

26 Copyright © 2012 Pearson Education, Inc. Outline Objectives 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

27 Copyright © 2012 Pearson Education, Inc. Objectives Develop problem-solving solutions in C++ containing: Simple arithmetic computations Information printed on the screen User-supplied Information from keyboard Programmer-defined data types

28 C++ Program Structure /*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */ #include // Required for cout, endl. #include // 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.

29 /*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */ #include // Required for cout, endl. #include // 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 */

30 /*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */ #include // Required for cout, endl. #include // 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

31 /*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */ #include // Required for cout, endl. #include // 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.

32 /*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */ #include // Required for cout, endl. #include // 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.

33 /*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */ #include // Required for cout, endl. #include // 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.

34 /*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */ #include // Required for cout, endl. #include // 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.

35 /*-------------------------------------------------------- * Program chapter1_1 * This program computes the distance between two points. */ #include // Required for cout, endl. #include // 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.

36 Constants and Variables Copyright © 2012 Pearson Education, Inc.

37 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.

38 Initial Values C++ does not provide initial values for variables. –Thus using the value of a variable before it is initialized may result in ‘garbage’. Copyright © 2012 Pearson Education, Inc.

39 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.

40 Valid C++ Identifiers Must begin with an alphabetic character 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.

41 C++ Keywords Copyright © 2012 Pearson Education, Inc.

42 C++ Identifiers Should be carefully chosen to reflect the 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.

43 Common C++ Data Types KeywordExample of a constant –booltrue –char'5' –int25 –double25.0 –string"hello" // #include Copyright © 2012 Pearson Education, Inc.

44 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)]; Examples double x1, y1(0); int counter=0; const int MIN_SIZE=0; bool error(false); char comma(',');

45 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.

46 C++ Classes Copyright © 2012 Pearson Education, Inc.

47 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.

48 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.

49 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.

50 Class Syntax Copyright © 2012 Pearson Education, Inc.

51 Using a Class Once a class is defined, you may use the class as a type specifier. –You must include the class definition (i.e. header file) Copyright © 2012 Pearson Education, Inc.

52 C++ Operators Copyright © 2012 Pearson Education, Inc.

53 Assignment Operator The assignment operator (=) is used in 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.

54 Order of Types Because different types are different representations, 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 double double float long integer integer short integer

55 Assignment Statements Assignment operators must not be confused with equality. Copyright © 2012 Pearson Education, Inc.

56 Arithmetic Expressions Expressions appearing in assignment statements 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.

57 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.

58 Operator Basics The five operators (* / % + -) are binary 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.

59 Integer Division Division between two integers results in 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.

60 Mixed Operations Binary operations on two values of same 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.

61 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

62 Overflow and Underflow Overflow –answer too large to store Example: using 16 bits for integers result = 32000 +532; Exponent overflow –answer’s exponent is too large Example: using float, with exponent range –38 to 38 result = 3.25e28 * 1.0e15; Exponent underflow –answer’s exponent too small Example: using float, with exponent range –38 to 38 result = 3.25e-28 *1.0e-15; Copyright © 2012 Pearson Education, Inc.

63 Increment and Decrement Operators Increment Operator ++ post incrementx++; pre increment++x; Decrement Operator - - post decrementx- -; 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.

64 Abbreviated Assignment Operators operatorexampleequivalent 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.

65 Operator Precedence Copyright © 2012 Pearson Education, Inc. PrecedenceOperatorAssociativity 1Parenthesis: ()Innermost First 2Unary operators: + - ++ -- (type) Right to left 3Binary operators: * / % Left to right 4Binary operators: + - Left to right 5Assignment Operators = += -= *= /= %= Right to left

66 Standard Input / Output Copyright © 2012 Pearson Education, Inc.

67 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.

68 Simple Input - cin cin is an istream object defined in 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 Form cin >> identifier >> identifier; Note: Data entered from the keyboard must be compatible with the data type of the variable. Copyright © 2012 Pearson Education, Inc.

69 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 c 39 b Memory Snapshot xch 45‘c’ 39‘\n ’

70 Manipulators and Methods endl – places a newline character in the output buffer and flushes the buffer. setf() and unsetf() Copyright © 2012 Pearson Education, Inc. FlagMeaning ios::showpointdisplay the decimal point ios::fixedfixed decimal notation ios::scientificscientific 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 the next value to the integer value n ios::rightright justification ios::leftleft justification

71 Building C++ Solutions with IDEs Copyright © 2012 Pearson Education, Inc.

72 Integrated Development Environments (IDEs) IDEs are software packages designed to facility the development of software solutions. IDEs include: –Code editors –Compiler –Debugger –Testing tools –Many additional helpful tools… Copyright © 2012 Pearson Education, Inc.

73 Basic Functions in C++ Standard Library Copyright © 2012 Pearson Education, Inc.

74 Basic C++ Math Functions Copyright © 2012 Pearson Education, Inc. fabs(x)computes absolute value of x sqrt(x)computes square root of x, where x >=0 pow(x,y)computes x y ceil(x)nearest integer larger than x floor(x)nearest integer smaller than x exp(x)computes e x log(x)computes ln x, where x >0 log10(x)computes log 10 x, where x>0

75 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 [−π, π].

76 Common Functions Defined in 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.

77 Copyright © 2012 Pearson Education, Inc. Problem Solving Applied

78 Copyright © 2012 Pearson Education, Inc.

79

80 System Limitations Copyright © 2012 Pearson Education, Inc.

81 System Limitations C++ standards do not specify limitations of data types – they are compiler-specific. C++ does provide standard methods of accessing the limits of the compiler: – defines ranges of integer types. – defines ranges of floating-point types. –the sizeof(type) function returns the memory size of the type, in bytes. Copyright © 2012 Pearson Education, Inc.


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

Similar presentations


Ads by Google