Overview of C++ Chapter 2 2.1 C++ Language Elements Comments make a program easier to understand // Used to signify a comment on a single line /* Text text */ use if comments on multi lines Don’t embed comments within /* */ comments 2 Compiler Directives #include – Compiler directive – (Pre-)Processed at compilation time – Instructs compiler on what you want to include in the program #include <iostream> – Adds library files to program – Used with < > – Also “ “ user defined 3 Compiler Directives Stream data type – Delivers objects that are streams of characters – Defined in iostream – Entered on the keyboard (cin) – Displayed on monitor (cout) 4 Namespace std Name region Standard library is defined in std Always: using namespace std; Attention for the “;” after the declaration Compare: No “;” for include directives Should follow include-lines 5 The Function “main” Form: – int main() Indicates where the program starts Must be included in EVERY C++ program Function: A named sequence of statements which can be called and parameterized. int: Return type of the program (for the operating system) 6 Declarations Function body: – Declaration statements – Executable statements Declarations specify data needs (data identifiers) Each identifier needed must be declared – const float Km_Per_Mile = 1.609; Comma used to separate identifiers – float miles, km; cin and cout are undeclared identifiers – Special elements called streams (included with the iostream) – cin - input stream , cout - output stream 7 Executable Statements cout diplays output – cout << “Enter the fabric size in square meters: ”; cin gets input – cin >> sizeInSqmeters; Assignment – sizeInSqyards = metersToYards * sizeInSqmeters; 8 2.2 Reserved Words and Identifiers Reserved words have special meanings – Can NOT be used for other purposes (const, float and void are some examples) Identifiers (variables) – Used to store data by the program (user-defined) – Valid identifiers - letter, letter1, _letter – Invalid identifiers - 1letter, const, hell o 9 Reserved Words and Identifiers Special symbols – C++ has rules for special symbols – = * ; { } ( ) // << >> Appendix B – Examples of reserved words – Special characters 10 Upper and Lower Case C++ case sensitive – Compiler differentiates upper & lower case – Identifiers can be either – Be careful though (cost != Cost) Blank spaces and tabs – Use space to make program readable – Use care in placing spaces Usually (C-style): – Constants: Upper Case (e.g. TIME_TO_TRAVEL) – Identifier: Lower Case (e.g. time_to_travel or better timeToTravel) 11 2.3 Data Types and Declarations Data type: – Set of values an operations that can be performed on these values Predefined data types – int (integers) • Positive or negative whole numbers • -1000 12 199 100000 • INT_MAX - largest int allowed by compiler – float (real numbers) • Positive or negative decimal numbers • -10.5 1.2 100.02 99.88 12 Data Types and Declarations Predefined data types – bool (boolean) • true • false – char (Characters) • Represent characters (keyboard symbols) 13 Data Types and Declarations 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 Other integers types – short: typically uses less bits – long: typically uses more bits INT_MIN and INT_MAX 14 Data Types and Declarations Different types allow programmers to use resources more efficiently Standard arithmetic and relational operations are available for these types Operations: – – – – Addition Subtraction Multiplication … 15 Data Types and Declarations Floating-point types represent real numbers – Integer part – Fractional part The number 108.1517 breaks down into the following parts – 108 - integral part – 1517 - fractional part Examples -10.67 .6789 75. 3.366 16 Data Types and Declarations C++ provides three floating-point types – float – double – long double Scientific notation possible: 1.56*106 in C++: 1.56e6 or 1.56e+6 e: lower case exponent Exponent whole number (int) Fixed point format for integers binary number Floating point format for real number 0.5 <= mantissa <= 1.0 and an integer exponent (basis 2) 17 Data Types and Declarations 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) 18 Data Types and Declarations ASCII is the dominant encoding scheme 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 19 Why Data Types Compiler knows about correct values and operations Minimize resources Early failure detection Examples of failures: – n = true+false; – If(2 == ‘2’) 20 string Class 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 21 string Class String literal – “A” – “1234” – “Enter the distance” Additional data types included in library #include <string> – Various operations on strings – Compare, Join, Length, etc. 22 Declarations 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 23 Variable Declarations Variable: Name associated with a location in memory Variable declaration: Tells compiler the name and the type of the variable Examples – – – – – char response; float temperature; int i; string firstName; bool isAvailable; 24 Variable Declarations Form: Type identifier_list; Examples int index, value; string gender = “male”; Compiler allocates storage for each variable in the list using the specified data type information. 25 Constant Declarations Types of constants – – – – – integer float char bool string objects Associate meaningful terms – const float PAYRATE = 10.25; Interpretation similar to variables with the constraint that constants can not be changed (read-only!). 26 Hello.cpp // FILE: Hello.cpp // DISPLAYS A USER'S NAME #include <iostream> #include <string> using namespace std; int main () { 27 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; } 28 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++. 29 2.4 Executable Statements Executable Statement: C++ statement that is translated into a sequence of machine language instructions. Memory status: e.g. miles-to-km conversion program – Before execution: – After execution: miles = ? kms = ? miles = 10.00 kms = 16.09 Assignments – Form: result = expression; – kms = KM_PER_METER * miles; – sum = sum + item; 30 2.4 Executable Statements Example 1: kms = KM_PER_METER * miles; Before assignment After assignment KMS_PER_ MILE 1.609 1.609 * miles 10.00 10.00 kms ? 16.09 31 2.4 Executable Statements Example 2: x = x + n; Not an algebraic equation!! Before assignment After assignment x 20 25 + n 5 5 32 Arithmetic Operators + * / % Addition Subtraction Multiplication Division Modulus 33 Input / Output Operations Input – #include <iostream> library – cin >> sizeInSqmeters; Extracted from cin (input stream) >> Directs input to variable cin associated with keyboard input (stdin) Used with int, float, char, bool and strings 34 Data Types and cin Don’t mix types with cin int x; cin >> x; Keyboard input 16.6 Value placed in x would be 16 35 Other Characteristics of cin Leading blanks ignored (floats, int, char, bool and strings) Char read 1 at a time (1 non blank) int or float will read until space or carriage return Stings same as int and float 36 General Form for cin Form: cin >> dataVariable; cin >> age >> firstInitial; How does the user know when to type in some data? Your program must prompt for that (output) 37 Program Output Output stream cout << Output operator (insertion operator) – cout << “my height in inches is: “ << height; Blank lines – endl; or “\n”; Form: cout << dataVariable; Example: cout << “Hello Mr. “ << name << “ !!\n” 38 Return Statement Form: return expression; Expression: – – – – Literal Variable Arithmetic Logic Examples: return 0; return x + z; Return: Transfers control to the caller of the function (in case of the function main the caller is the operating system) 39 2.5 General Form of a C++ Program 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 40 General Form of a C++ Program General form of function body parts – Declaration statements • Variables and constants – Executable statements • C++ statements 41 General Form of a C++ Program General form // File: filename // Program description: #include directives int main() { Declarations section Executable statements section } 42 General Form // Name: Mike Hudock // Date: March 10, 2000 // Files: file1.cpp file2.cpp // Changes : // Program description: 43 General Form Use comments throughout code to highlight points of interest Avoid strange identifiers Function explanations Algorithm definitions 44 2.6 Arithmetic Expressions int data type – + - * /, Assignment, input and output on int – % Only used with int 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 45 Modulus and Integer Used only with integer and yields remainder Examples of integer modulus 7%2=1 299 % 100 = 99 49 % 5 = 4 33%-2 varies among implementations (avoid negative numbers!) 15 % 0 undefined 0<= m%n < n Relationship: m == (m/n)*n + m%n 46 Mixed-type Assignments Mixed-type expression: An expression including operands of type int and float. 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. Examples: 5/2 is int, 5/2.0 is float 47 Mixed-type Assignments Conversion from int to float is needed in evaluating mixed-type expressions. Eg. 5/2.0 becomes 5.0/2.0 Assignment: First right side is evaluated, then the result is assigned to the left side. Examples for mixed-type assignments: float rate = 100; rate = 100/3; // Value of rate: 100.0 // Value of rate: 33.0 // (common error: rate = 33.33..) 48 Mixed-type Assignments 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 49 Expressions With Multiple Operators Operator precedence tells how to evaluate expressions 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 50 Evaluation of Expressions z - (a + b ) + w * -y (all variables are int) 2 C++ notation: z – (a+b/2)+w*-y 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 51 Evaluation of Expressions Mixed-type evaluation is more tricky! Example: int m, k; float x; k = 5; x = 5.5; m = x + k/2 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 52 Coin Collection Case Study 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. 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 53 Coin Collection Case Study Analysis (cont) – Use modulus % to get cents value – % 100 Design – – – – – Prompt for name Get count of nickels and pennies Compute total value Calculate dollars and cents Display results 54 Coin Collection Case Study Implementation – Write C++ code of design – Verify correct data types needed – Mixed mode types and promotion Testing – Test results using various input combinations 55 Coins.cpp // File: coins.cpp // Determines the value of a coin collection #include <iostream> #include <string> using namespace std; int main() { 56 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; 57 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; 58 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; } 59 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. 60 2.7 Interactive Mode, Batch and Data Files Two modes interactive or batch – Keyboard input interactive Batch mode data provided prior to start – File as input Input / output redirection – Direct input to program use ‘<‘ symbol – Direct output to a file use ‘>‘ symbol – Operating system dependent 61 Input / Output Redirection Input: – Program name < datafile – Unix: metric awaits data from keyboard metric < mydata now from a file named mydata 62 Input / Output Redirection Output: – Program name > outFile – metric > outFile Input and output redirection – metric < inFile > outFile 63 Milesbatch.cpp // File: milesBatch.cpp // Converts distance in miles to kilometers. #include <iostream> using namespace std; int main() // start of main function { const float KM_PER_MILE = 1.609; float miles, kms; 64 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; } 65 Milesbatch.cpp Program output The distance in miles is 10 The distance in kilometers is 16.09 66 2.8 Common Programming Errors Programming Errors – Very common – “Bugs” term for software errors – Debugging: process of detecting and removing bugs. Syntax Errors – Violation of grammatical rules e.g. use of variable without declaring it first. – Systematic solutions – Errors vs. Warnings Compiler not descriptive – Look at line number before and after error – Watch missing ; and } 67 Common Programming Errors Run-time errors – Illegal operation (divide by 0) – Even when a program is syntactically correct, run-time errors may occur. – Debugging can help 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. 68