Presentation is loading. Please wait.

Presentation is loading. Please wait.

Overview of C++ Chapter 2. 2 2.1 C++ Language Elements t Comments make a program easier to understand t // Used to signify a comment on a single line.

Similar presentations


Presentation on theme: "Overview of C++ Chapter 2. 2 2.1 C++ Language Elements t Comments make a program easier to understand t // Used to signify a comment on a single line."— Presentation transcript:

1 Overview of C++ Chapter 2

2 2 2.1 C++ Language Elements t Comments make a program easier to understand t // Used to signify a comment on a single line t /* Text text */ use if comments on multi lines t Don’t embed comments within /* */ comments

3 3 Compiler Directives t #include –Compiler directive –(Pre-)Processed at compilation time –Instructs compiler on what you want to include in the program t #include –Adds library files to program –Used with –Also “ “ user defined

4 4 Compiler Directives t Stream data type –Delivers objects that are streams of characters –Defined in iostream –Entered on the keyboard(cin) –Displayed on monitor(cout)

5 5 Namespace std t Name region t Standard library is defined in std t Always: using namespace std; t Attention for the “;” after the declaration t Compare: No “;” for include directives t Should follow include-lines

6 6 The Function “main” t Form: –int main() t Indicates where the program starts t Must be included in EVERY C++ program t Function: A named sequence of statements which can be called and parameterized. t int: Return type of the program (for the operating system)

7 7 Declarations t Function body: –Declaration statements –Executable statements t Declarations specify data needs (data identifiers) t Each identifier needed must be declared –const float Km_Per_Mile = 1.609; t Comma used to separate identifiers –float miles, km; t cin and cout are undeclared identifiers –Special elements called streams (included with the iostream) –cin - input stream, cout - output stream

8 8 Executable Statements t cout diplays output –cout << “Enter the fabric size in square meters: ”; t cin gets input –cin >> sizeInSqmeters; t Assignment –sizeInSqyards = metersToYards * sizeInSqmeters;

9 9 2.2 Reserved Words and Identifiers t Reserved words have special meanings –Can NOT be used for other purposes (const, float and void are some examples) t Identifiers (variables) –Used to store data by the program (user-defined) –Valid identifiers - letter, letter1, _letter –Invalid identifiers - 1letter, const, hell o

10 10 Reserved Words and Identifiers t Special symbols –C++ has rules for special symbols –= * ; { } ( ) // > t Appendix B –Examples of reserved words –Special characters

11 11 Upper and Lower Case t C++ case sensitive –Compiler differentiates upper & lower case –Identifiers can be either –Be careful though (cost != Cost) t Blank spaces and tabs –Use space to make program readable –Use care in placing spaces t Usually (C-style): –Constants: Upper Case (e.g. TIME_TO_TRAVEL) –Identifier: Lower Case (e.g. time_to_travel or better timeToTravel)

12 12 2.3 Data Types and Declarations t Data type: –Set of values an operations that can be performed on these values t Predefined data types –int(integers) Positive or negative whole numbers -1000 12199100000 INT_MAX- largest int allowed by compiler –float(real numbers) Positive or negative decimal numbers -10.51.2100.0299.88

13 13 Data Types and Declarations t Predefined data types –bool(boolean) true false –char(Characters) Represent characters (keyboard symbols)

14 14 Data Types and Declarations t The basic integer type is int –The size of an int depends on the machine and the compiler On pc’s it is normally 16 or 32 bits t Other integers types –short: typically uses less bits –long: typically uses more bits t INT_MIN and INT_MAX

15 15 Data Types and Declarations t Different types allow programmers to use resources more efficiently t Standard arithmetic and relational operations are available for these types t Operations: –Addition –Subtraction –Multiplication –…

16 16 Data Types and Declarations t Floating-point types represent real numbers –Integer part –Fractional part t The number 108.1517 breaks down into the following parts –108 - integral part –1517 - fractional part t Examples -10.67.678975.3.366

17 17 Data Types and Declarations t C++ provides three floating-point types –float –double –long double t Scientific notation possible: 1.56*10 6 in C++: 1.56e6 or 1.56e+6 t e: lower case exponent t Exponent whole number (int) t Fixed point format for integers  binary number t Floating point format for real number  0.5 <= mantissa <= 1.0 and an integer exponent (basis 2)

18 18 Data Types and Declarations t Predefined data types –char(characters) Individual character value (letter or number) Character literal enclosed in single quotes ‘A’ Escape sequences: ‘\n’ ‘\b’ ‘\r’ ‘\t’ ‘\\’ –bool(true / false)

19 19 Data Types and Declarations t ASCII is the dominant encoding scheme t One byte a character (Unicode more bytes) –Examples ' ' encoded as 32 '+' encoded as 43 'A' encoded as 65 'Z' encoded as 90 ’a' encoded as 97 ’z' encoded as 122

20 20 Why Data Types t Compiler knows about correct values and operations t Minimize resources t Early failure detection t Examples of failures: –n = true+false; –If(2 == ‘2’)

21 21 string Class t String object data type –A literal string constant is a sequence of zero or more characters enclosed in double quotes – “I am a string\n" –Individual characters of string are stored in consecutive memory locations –The null character ('\0') is appended to strings so that the compiler knows where in memory strings ends

22 22 string Class t String literal –“A” –“1234” –“Enter the distance” t Additional data types included in library #include –Various operations on strings –Compare, Join, Length, etc.

23 23 Declarations t Identifiers should be –Short enough to be reasonable to type (single word is norm) Standard abbreviations are fine (but only standard abbreviations) –Long enough to be understandable When using multiple word identifiers capitalize the first letter of each word

24 24 Variable Declarations t Variable: Name associated with a location in memory t Variable declaration: Tells compiler the name and the type of the variable t Examples –char response; –float temperature; –int i; –string firstName; –bool isAvailable;

25 25 Variable Declarations t Form: Type identifier_list; t Examples int index, value; string gender = “male”; t Compiler allocates storage for each variable in the list using the specified data type information.

26 26 Constant Declarations t Types of constants –integer –float –char –bool –string objects t Associate meaningful terms –constfloatPAYRATE = 10.25; t Interpretation similar to variables with the constraint that constants can not be changed (read-only!).

27 27 Hello.cpp // FILE: Hello.cpp // DISPLAYS A USER'S NAME #include using namespace std; int main () {

28 28 Hello.cpp char letter1, letter2; string lastName; // Enter letters and print message. cout << "Enter 2 initials and last name: "; cin >> letter1 >> letter2 >> lastName; cout << "Hello " << letter1 << ". " << letter2 << ". " << lastName << "! "; cout << "We hope you enjoy studying C++." << endl; return 0; }

29 29 Hello.cpp Program output Enter first two initials and last name and press return: EBKoffman Hello E. B. Koffman! We hope you enjoy studying C++.

30 30 2.4 Executable Statements t Executable Statement: C++ statement that is translated into a sequence of machine language instructions. t Memory status: e.g. miles-to-km conversion program –Before execution: miles = ?kms = ? –After execution:miles = 10.00kms = 16.09 t Assignments –Form: result = expression; –kms = KM_PER_METER * miles; –sum = sum + item;

31 31 2.4 Executable Statements t Example 1: kms = KM_PER_METER * miles; Before assignmentAfter assignment 1.609 10.00 1.609 10.00 KMS_PER_ MILE miles kms ?16.09 *

32 32 2.4 Executable Statements t Example 2: x = x + n;Not an algebraic equation!! Before assignmentAfter assignment 20 5 25 5 x n +

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

34 34 Input / Output Operations t Input –#include library –cin >> sizeInSqmeters; t Extracted from cin (input stream) t >> Directs input to variable t cin associated with keyboard input (stdin) t Used with int, float, char, bool and strings

35 35 Data Types and cin t Don’t mix types with cin int x; cin >> x; Keyboard input 16.6 Value placed in x would be 16

36 36 Other Characteristics of cin t Leading blanks ignored (floats, int, char, bool and strings) t Char read 1 at a time (1 non blank) t int or float will read until space or carriage return t Stings same as int and float

37 37 General Form for cin t Form: cin >> dataVariable; cin >> age >> firstInitial; t How does the user know when to type in some data?  Your program must prompt for that (output)

38 38 Program Output t Output stream cout t << Output operator (insertion operator) –cout << “my height in inches is: “ << height; t Blank lines –endl; or “\n”; t Form:cout << dataVariable; t Example: cout << “Hello Mr. “ << name << “ !!\n”

39 39 Return Statement t Form: return expression; t Expression: –Literal –Variable –Arithmetic –Logic t Examples: return 0; return x + z; t Return: Transfers control to the caller of the function (in case of the function main the caller is the operating system)

40 40 2.5 General Form of a C++ Program t General program form –Function: basic unit (collection of related statements) –A C++ program must contain a main function void main () –int - function returns integer value –main - lower case with () –{ } - Braces define the function body

41 41 General Form of a C++ Program t General form of function body parts –Declaration statements Variables and constants –Executable statements C++ statements

42 42 General Form of a C++ Program t General form // File: filename // Program description: #include directives int main() { Declarations section Executable statements section }

43 43 General Form // Name: Mike Hudock // Date: March 10, 2000 // Files: file1.cpp file2.cpp // Changes : // Program description:

44 44 General Form t Use comments throughout code to highlight points of interest t Avoid strange identifiers t Function explanations t Algorithm definitions

45 45 2.6 Arithmetic Expressions t int data type –+ - * /, Assignment, input and output on int –% Only used with int t Examples of integer division (only integral part is considered) 15 / 3 = 5 15 / 2 = 7 17/-2 system dependent (avoid it!) 0 / 15 = 0 15 / 0 undefined

46 46 Modulus and Integer t Used only with integer and yields remainder t Examples of integer modulus 7 % 2 = 1 299 % 100 = 99 49 % 5 = 4 33%-2 varies among implementations (avoid negative numbers!) 15 % 0 undefined t 0<= m%n < n t Relationship: m == (m/n)*n + m%n

47 47 Mixed-type Assignments t Mixed-type expression: An expression including operands of type int and float. t What is the type of an expression? –Variable type are specified in their declarations. –An expression is of type int iff all operands are of type int. –If at least one operand is float the expression becomes type float. t Examples: 5/2 is int, 5/2.0 is float

48 48 Mixed-type Assignments t Conversion from int to float is needed in evaluating mixed-type expressions. t Eg. 5/2.0 becomes 5.0/2.0 t Assignment: First right side is evaluated, then the result is assigned to the left side. t Examples for mixed-type assignments: float rate = 100;// Value of rate: 100.0 rate = 100/3;// Value of rate: 33.0 // (common error: rate = 33.33..)

49 49 Mixed-type Assignments t Another example: int n; n = 15.7 + 3.5; // Value of n is integral part of the // sum 19.2 which is 19  n = 19 // Be careful: n != 15 + 3 = 18

50 50 Expressions With Multiple Operators t Operator precedence tells how to evaluate expressions t Standard precedence order: –1. ( ): if nested then innermost first –2. Unary + - : if multiple then from right to left –3. * / %: If several then from left to right –4. Binary + -: If several then from left-to-right

51 51 Evaluation of Expressions t z - (a + b ) + w * -y (all variables are int) 2 t C++ notation: z – (a+b/2)+w*-y t 1. Rule 1  term a+b/2 first 2. Rule 3  / before +  evaluate b/2 3. Rule 4  evaluate a + b/2 4. Rule 2  evaluate –y 5. Rule 3  evaluate w*-y 6. Rule 4  evaluate z – (a+b/2) [left first!] 7. Rule 4  evaluate whole expression

52 52 Evaluation of Expressions t Mixed-type evaluation is more tricky! t Example: int m, k; float x; k = 5; x = 5.5; m = x + k/2 t Evaluation: 1. Rule 3  / before +  evaluate k/2 and get 2 (since k is int!) 2. Rule 4  evaluate the whole expression: 2.1 convert 2 to 2.0 2.2 get the sum 7.5 2.3 convert back to int 2.4 store integral part 7 in m

53 53 Coin Collection Case Study t Problem statement –Saving nickels and pennies and want to exchange these coins at the bank so need to know the value of coins in dollars and cents. t Analysis –Count of nickels and pennies in total –Determine total value 1 penny = 1 cent 1 nickel = 5 pennies –Use integer division to get dollar value / 100

54 54 Coin Collection Case Study t Analysis (cont) –Use modulus % to get cents value –% 100 t Design –Prompt for name –Get count of nickels and pennies –Compute total value –Calculate dollars and cents –Display results

55 55 Coin Collection Case Study t Implementation –Write C++ code of design –Verify correct data types needed –Mixed mode types and promotion t Testing –Test results using various input combinations

56 56 Coins.cpp // File: coins.cpp // Determines the value of a coin collection #include using namespace std; int main() {

57 57 Coins.cpp // Local data... string name; int pennies; int nickels; int dollars; int change; int totalCents; // Prompt sister for name. cout << "Enter your first name: "; cin >> name;

58 58 Coins.cpp // Read in the count of nickels and pennies. cout << "Enter the number of nickels: "; cin >> nickels; cout << "Enter the number of pennies: "; cin >> pennies; // Compute the total value in cents. totalCents = 5 * nickels + pennies; // Find the value in dollars and change. dollars = totalCents / 100; change = totalCents % 100;

59 59 Coins.cpp // Display the value in dollars and change. cout << "Good work " << name << '!' << endl; cout << "Your collection is worth " << dollars << " dollars and " << change << " cents." << endl; return 0; }

60 60 Coins.cpp Program output Enter your first name and press return: Sally Enter number of nickels and press return: 30 Enter number of pennies and press return: 77 Good work sally! Your collection is worth 2 dollars and 27 cents.

61 61 2.7 Interactive Mode, Batch and Data Files t Two modes interactive or batch –Keyboard input interactive t Batch mode data provided prior to start –File as input t Input / output redirection –Direct input to program use ‘<‘ symbol –Direct output to a file use ‘>‘ symbol –Operating system dependent

62 62 Input / Output Redirection t Input: –Program name < datafile –Unix: metric  awaits data from keyboard metric < mydata  now from a file named mydata

63 63 Input / Output Redirection t Output: –Program name > outFile –metric > outFile t Input and output redirection –metric outFile

64 64 Milesbatch.cpp // File: milesBatch.cpp // Converts distance in miles to kilometers. #include using namespace std; int main() // start of main function { const float KM_PER_MILE = 1.609; float miles, kms;

65 65 Milesbatch.cpp // Need not prompt user since input from a file // Get the distance in miles. cin >> miles; cout << "The distance in miles is " << miles << endl; // Convert the distance to kilometers. kms = KM_PER_MILE * miles; // Display the distance in kilometers. cout << "The distance in kilometers is " << kms << endl; return 0; }

66 66 Milesbatch.cpp Program output The distance in miles is 10 The distance in kilometers is 16.09

67 67 2.8 Common Programming Errors t Programming Errors –Very common –“Bugs” term for software errors –Debugging: process of detecting and removing bugs. t Syntax Errors –Violation of grammatical rules e.g. use of variable without declaring it first. –Systematic solutions –Errors vs. Warnings t Compiler not descriptive –Look at line number before and after error –Watch missing ; and }

68 68 Common Programming Errors t Run-time errors –Illegal operation (divide by 0) –Even when a program is syntactically correct, run-time errors may occur. –Debugging can help t Logic errors –Program functions differently than you expect Wrong solution for a given (sub)problem !!! –Thorough testing and desk checking or step-by-step debugging can help.


Download ppt "Overview of C++ Chapter 2. 2 2.1 C++ Language Elements t Comments make a program easier to understand t // Used to signify a comment on a single line."

Similar presentations


Ads by Google