Lecture 1 C++ Fundamentals 1.1 Introduction to C++ 1.2 Structure chart, Flowchart and Pseudo code 1.3 Debugging and documentation techniques 1.4 Variables and Assignments 1.5 Input and Output 1.6 Data Types and Expressions
1.1 Introduction to C++ Where did C++ come from? Derived from the C language C was derived from the B language B was derived from the BCPL( Basic Combined Programming Language ) language C developed by Dennis Ritchie at AT&T( American Telephone & Telegraph Company ) Bell Labs in the 1970s. Used to maintain UNIX systems Many commercial applications written in C C++ developed by Bjarne Stroustrup at AT&T Bell Labs in the 1980s. Overcame several shortcomings of C Incorporated object oriented programming C remains a subset of C++ 2
C++ program Basic C++ structure A normal C++ programs has 3 components Preprocessor User defined Main function 1) Preprocessor e.g.: #include< iostream > Usually used to indicate other files (libraries) to compile and defining constants 2) User defined (function, class, etc) e.g.: void printHello () { cout << “Hello”; } Used when user requires creation of problem specific solution 3) Main function e.g.: int main() {…} Every program in C++ must have one and only one main function
A Simple C++ Program A simple C++ program begins this way #include < iostream > using namespace std; int main() { And ends this way return 0; } 4
5 Comments Comments are pieces of source code discarded from the code by the compiler. They do nothing. Their purpose is only to allow the programmer to insert notes or descriptions embedded within the source code. C++ supports two ways to insert comments: // line comment /* block comment */ /* my second program in C++ with more comments */ #include <iostream> int main () { cout << "Hello World! "; // says Hello World! return 0; }
6 My first program in C++ // my first program in C++ #include <iostream> using namespace std; int main () { cout << "Hello World!"; return 0; } Hello World! a comment line a pound sign (#) is a directive for the preprocessor. It is not executable code but indications for the compiler. tells the compiler's preprocessor to include the iostream standard header file. Corresponds to the beginning of the main function declaration. The main function is the point where all C++ programs begin their execution. cout is the standard output stream in C++ to terminate a program
Layout of a Simple C++ Program #include < iostream > using namespace std; int main() { variable_declarations statement_1 statement_2 … statement_last return 0; } 7
Program Layout (1/2) Programmers format programs so they are easy to read Place opening brace ‘{‘ and closing brace ‘}’ on a line by themselves Indent statements Use only one statement per line 8
Program Layout (2/2) Variables are declared before they are used Typically variables are declared at the beginning of the program Statements (not always lines) end with a semi-colon Include Directives #include <iostream> Tells compiler where to find information about items used in the program iostream is a library containing definitions of cin and cout 9
Program Layout using namespace std; Tells the compiler to use names in iostream in a “standard” way To begin the main function of the program int main() { To end the main function return 0; } Main function ends with a return statement 10
Concepts Compiler : is a program that translates a high-level language program, such as a C++ program, into a machine-language program that the computer can directly understand and execute. Linking : The object code for your C++ program must be combined with the object code for routines (such as input and output routines) that your program uses. This process of combining object code is called linking and is done by a program called a linker. For simple programs, linking may be done for you automatically.
Running a C++ Program C++ source code is written with a text editor The compiler on your system converts source code to object code. The linker combines all the object code into an executable program. 12
Run a Program Write code Compile the code Fix any errors the compiler indicates and re-compile the code Run the program Now you know how to run a program on your system 13
Knowledge Check What are the 3 main components of a C++ program? What is the purpose of the statement “ using namespace std ” ? Name the C++ library that can be called to process input and output of a program. Demonstrate 2 methods to write comments in a C++ program.
1.2 Structure Chart, Flowchart and Pseudo Code
Program Design Programming is a creative process No complete set of rules for creating a program There are many ways to solve the same problem Each student will have their own unique style Program Design Process Problem Solving Phase Result is an algorithm that solves the problem Implementation Phase Result is the algorithm translated into a programming language 16
Problem Solving Phase Be certain the task is completely specified What is the input? What information is in the output? How is the output organized? Develop the algorithm before implementation Experience shows this saves time in getting your program to run. Test the algorithm for correctness 17
Implementation Phase Translate the algorithm into a programming language Easier as you gain experience with the language Compile the source code Locates errors in using the programming language Run the program on sample data Verify correctness of results Results may require modification of the algorithm and program 18
19 19 Input Processing Output Names for our cells 5, 10 15 1) Declare variables input_1 input_2 sum 2) Assign values input_1 = 5 input_2 = 10 3) Process sum = input_1 + input_2 The computer (and so C++) provides basic arithmetic operations. If the operation you want to use is not provided, you have to compose it. Sample problems Write a program calculating the sum of two numbers
20 There are many models supporting the development of the code. We will see now the same algorithm expressed as: Pseudo code Structure diagram Flowcharts and finally in C++ (in program design: implementation phase). Write a program calculating the sum of two numbers
Pseudocode Mixture of C++ and ordinary English Allows us to make our algorithm precise without worrying about the details of C++ syntax 21
22 PROGRAM Add Two Numbers READ two numbers ADD the numbers WRITE the sum END PROGRAM Version 1: PROGRAM Add Two Numbers READ First READ Second COMPUTE Sum = First + Second WRITE Sum END PROGRAM Version 2: Write a program calculating the sum of two numbers Pseudocode
Some pseudocode keywords Compute Assign Increment, decrement Read, write, get, display – used when representing I/O If, then, else, switch – used when representing selection While, do, for – used when representing repetitions
Structure Diagram Helpful to break the algorithm into more manageable pieces Basic tree diagram that shows modules of the program 24 Version 1: PROGRAM Add Two Numbers READ Two Numbers ADD Two Numbers WRITE The Sum Write a program calculating the sum of two numbers
Structure Diagram 25 Version 2: PROGRAM Add Two Numbers READ Two Numbers ADD Two Numbers WRITE The Sum READ Input_1 READ Input_2 Sum = Input_1 + Input_2 Write a program calculating the sum of two numbers
Rules for Structure Diagram A module which resides above others is referred to as a Calling module A module which resides below another is referred to as a Called module A module can be both a calling and called module A called module can only be called by one calling module 26
Flowchart Diagram that shows the logical flow of a program Stress on structured programming Useful for planning each operation a program performs, and in order in which the operations are to occur By visualizing the process, a flowchart can quickly help identify bottlenecks or inefficiencies where the process can be streamlined or improved The final visualization can then be easily translated into a program 27
Flowchart Symbols Start/End terminal ( used to indicate the beginning and end of a program or module ) Input/Output operations ( used for all I/O operations ) Processes ( used for all arithmetic and data transfer operations ) Connector ( used to indicate the point at which a transfer of control operation occurs ) Off page connector ( used for connecting flowcharts on different pages ) Decision ( used to test for a condition ) Predefined process ( used to indicate the name process of a module to be executed )
Symbols Start/End terminal Usually labeled with the words Start or End Signify the start or end of the program or a process
Symbols Input/Output operations Signify data input or output Eg : Read height and weight from user, Display BMI on screen
Symbols Processes These are generic steps in a program such as mathematical computation Eg : bmi = weight / height / height
Symbols Connector Used when page is not long enough and shows a break/continuation in the program. Is numbered for identification
Symbols Off page connector Same purpose as a connector, but used when both parts are not of the same page Also must be numbered
Symbols Decision Asks a true/false question Has 1 input, and usually 2 output lines Eg : BMI more than 23? If true, then you are overweight If false, then you have healthy weight
Symbols Predefined process Represents a module/function Usually your own self defined functions Use to help break-down the flowchart into smaller parts
Flowchart Symbols … cont And all flowchart symbols are joined by the directional arrow. Without a direction, we cannot see the flow in the flowchart. Common mistakes: Not labeling output paths of a decision Not writing a question in the decision symbol Connecting the flowchart using lines instead of arrows
37 READ First READ Second Sum = First + Second WRITE Sum Write a program calculating the sum of two numbers START END
Each symbol denotes a type of operation. A note is written inside each symbol to indicate the specific function to be performed. The symbols are connected by flow-lines. Flowcharts are drawn and read from top to bottom unless a specific condition is met that alters the path. A sequence of operations is performed until a terminal symbol designates the sequence's end or the end of the program. Sometimes several steps or statements are combined in a single processing symbol for ease of reading. 38 Flowchart Conventions
39 A flowchart to accept two numbers as input and prints out the maximum start Input A Input B A > B print A print B end True False
Structured Programming Structured Programming is a technique using logical control constructs that make programs easier to read, debug, and modify if changes are required. Böhm and Jacopini states that any program can be written only using 3 control structures: Sequence Selection Repetition 40
Structured Programming … cont Sequence One statement is executed after another E.g.
Structured Programming … cont Selection Executing 1 possible output path based on evaluation of a condition E.g. True False
Structured Programming … cont Repetition Statements are executed repeatedly until a condition becomes True/False E.g. False True
Different selection structures 44 A>10 S1 true false true false 1) If a > 10 then do S1 S1 S2 A>10 3) If a > 10 then do S1 else do S2 true false S2 A>10 2) If a > 10 then do nothing else do S2 False True S1 A<=10 4) If a <= 10 then do S1
Different selection structures… cont In the previous slide, #1, #2 and #4 are all the same type of selection structure – IF #3 was an example of selection structure type IF-ELSE Another type of selection structure is SWITCH A S1 S2 CASE grade S3 S4 C D B If grade is: A, do S1 B, do S2 C, do S3 D, do S4
Different selection structures… cont Another way to represent switch If grade is: A, do S1 B, do S2 C, do S3 D, do S4 grade = “A” grade = “B” grade = “C” grade = “D” S1 break S2 break S3 break S4 break
Repetition (loop) structures 47 A<=10 S1 S2 true A<=10 S1 S2 true Repeat S1 S2 As long as A is Less than or equal to 10 otherwise exit the loop False False While A is less than or equal to 10 repeat S1 S2 End loop What is the difference ?
Loop example (do..While) 48 c<=5 Sum = Sum + A C = C + 1 true Draw a flowchart to allow the input of 5 numbers and display the sum of these numbers Input A Start C = 1 Sum=0 Output Sum End False Assume the numbers given to A are 3,2,4,5,6 in order C=1 Sum = 0 C=1 Sum = 0 A=3 C=1 Sum = 3 A=3 1 2 3 4 5 6 7 1,2 3 4 C=2 Sum = 3 A=3 5 C=2 Sum = 3 A=3 C <=5 true 6 C=2 Sum = 3 A=2 C=2 Sum = 5 A=2 3 4 C=3 Sum = 5 A=2 5 C=3 Sum = 5 A=3 C <=5 true 6 C=3 Sum = 5 A=4 C=3 Sum = 9 A=4 3 4 C=4 Sum = 9 A=4 5
Loop example (while…) 49 c<=5 Sum = Sum + A C = C + 1 true Draw a flowchart to allow the input of 5 numbers and displays out the sum of these numbers Input A Start C = 1 Sum=0 Output Sum End False Assume the numbers given to A are 3,2,4,5,6 in order C=1 C=1 Sum = 0 1 2 3 4 5 6 7 1 2 C=1 Sum = 0 C <=5 true C=1 Sum = 3 A=3 C=1 Sum = 3 A=3 3 4 C=2 Sum = 3 A=3 5 6 C=2 Sum = 3 C <=5 true C=2 Sum = 3 A=2 C=2 Sum = 5 A=2 3 4 C=3 Sum = 5 A=3 5 6
Prime number example flowchart 50 Pseudocode algorithm to solve this problem: 1. Start 2. Input a number M 3. Set an Index (I) to start from 2 4. Divide the number M by the Index (I) value and store the remainder in R 5. If R is equal to zero then output “Not Prime” and goto to Step 10 6. Increment Index (I) by 1 7. If the Index (I) value is less than the number M go to Step 4 8. Output “Prime” 9. End R=0? I = I + 1 True Input M Start I = 2 R=M%I Output Prime End False I<M? Output Not Prime True False 1 2 3 4 5 6 7 8 9
Find the Maximum 51
Find the Maximum - Structured 52
Find the Maximum - Structured 53
Unstructured Flowchart 54 break… Pseudocode
Knowledge Check Draw and describe as many of the flowchart symbols as you can. Write the pseudocode for a simple pizza ordering process. Name the 3 control structures in structured programming and illustrate what they are.
1.3 Debugging and Documentation Techniques
Testing and Debugging Bug A mistake in a program Debugging Eliminating mistakes in programs Term used when a moth caused a failed relay on the Harvard Mark 1 computer. Grace Hopper and other programmers taped the moth in logbook stating: “First actual case of a bug being found.” Slide 1- 57
Program Errors Syntax errors Violation of the grammar rules of the language Discovered by the compiler Error messages may not always show correct location of errors Run-time errors Error conditions detected by the computer at run-time Logic errors Errors in the program’s algorithm Most difficult to diagnose Computer does not recognize an error Slide 1- 58
1.4 Variables and Assignments
Variables and Assignments Variables are like small blackboards We can write a number on them We can change the number We can erase the number C++ variables are names for memory locations We can write a value in them We can change the value stored there We cannot erase the memory location Some value is always there Slide 2- 60
Slide 2- 61
Slide 2- 62
Identifiers Variables names are called identifiers Choosing variable names Use meaningful names that represent data to be stored First character must be a letter the underscore character Remaining characters must be letters numbers underscore character Slide 2- 63
Keywords Keywords (also called reserved words) Are used by the C++ language Must be used as they are defined in the programming language Cannot be used as identifiers Slide 2- 64
Declaring Variables (Part 1) Before use, variables must be declared Tells the compiler the type of data to store Examples: int number_of_bars ; double one_weight , total_weight ; int is an abbreviation for integer. could store 3, 102, 3211, -456, etc. number_of_bars is of type integer double represents numbers with a fractional component could store 1.34, 4.0, -345.6, etc. one_weight and total_weight are both of type double
Declaring Variables (Part 2) Immediately prior to use int main() { … int sum; sum = score1 + score 2; … return 0; } Slide 2- 66 At the beginning int main() { int sum; … sum = score1 + score2; … return 0; } Two locations for variable declarations
Assignment Statements An assignment statement changes the value of a variable total_weight = one_weight + number_of_bars; total_weight is set to the sum one_weight + number_of_bars Assignment statements end with a semi-colon The single variable to be changed is always on the left of the assignment operator ‘=‘ On the right of the assignment operator can be Constants -- age = 21; Variables -- my_cost = your_cost; Expressions -- circumference = diameter * 3.14159; Slide 2- 68
Assignment Statements and Algebra The ‘=‘ operator in C++ is not an equal sign The following statement cannot be true in algebra number_of_bars = number_of_bars + 3; In C++ it means the new value of number_of_bars is the previous value of number_of_bars plus 3 Slide 2- 69
Initializing Variables Declaring a variable does not give it a value Giving a variable its first value is initializing the variable Variables are initialized in assignment statements double mpg; // declare the variable mpg = 26.3; // initialize the variable Declaration and initialization can be combined using two methods Method 1 double mpg = 26.3, area = 0.0 , volume; Method 2 double mpg(26.3), area(0.0), volume; Slide 2- 70
Knowledge Check Declare 2 integer variables called num1 and num2. What data type should be used to represent height, weight and age? Declare and initialize a variable that will be used to store the salary of an employee.
1.5 Input and Output
Input and Output A data stream is a sequence of data Typically in the form of characters or numbers An input stream is data for the program to use Typically originates at the keyboard at a file An output stream is the program’s output Destination is typically the monitor a file Slide 2- 73
Output using cout cout is an output stream sending data to the monitor The insertion operator "<<" inserts data into cout Example: cout << number_of_bars << " candy bars\n"; This line sends two items to the monitor The value of number_of_bars The quoted string of characters " candy bars\n" Notice the space before the ‘c’ in candy The ‘\n’ causes a new line to be started following the ‘s’ in bars A new insertion operator is used for each item of output Slide 2- 74
Examples Using cout This produces the same result as the previous sample cout << number_of_bars ; cout << " candy bars\n"; Here arithmetic is performed in the cout statement cout << "Total cost is $" << (price + tax); Quoted strings are enclosed in double quotes ("Walter") Don’t use two single quotes (') A blank space can also be inserted with cout << " " ; if there are no strings in which a space is desired as in " candy bars\n" Slide 2- 75
Include Directives Include Directives add library files to our programs To make the definitions of the cin and cout available to the program: #include <iostream> Using Directives include a collection of defined names To make the names cin and cout available to our program: using namespace std; Slide 2- 76
Escape Sequences Escape sequences tell the compiler to treat characters in a special way '\' is the escape character To create a newline in output use \n – cout << "\n"; or the newer alternative cout << endl; Other escape sequences: \t -- a tab \\ -- a backslash character \" -- a quote character Slide 2- 77
Formatting Real Numbers Real numbers (type double) produce a variety of outputs double price = 78.5; cout << "The price is $" << price << endl; The output could be any of these: The price is $78.5 The price is $78.500000 The price is $7.850000e01 The most unlikely output is: The price is $78.50 Slide 2- 78
Showing Decimal Places cout includes tools to specify the output of type double To specify fixed point notation setf ( ios ::fixed) To specify that the decimal point will always be shown setf ( ios :: showpoint ) To specify that two decimal places will always be shown precision(2) Example: cout.setf ( ios ::fixed); cout.setf ( ios :: showpoint ); cout.precision (2); cout << "The price is " << price << endl ; Slide 2- 79
Input Using cin cin is an input stream bringing data from the keyboard The extraction operator (>>) removes data to be used Example: cout << "Enter the number of bars in a package\n"; cout << " and the weight in ounces of one bar.\n"; cin >> number_of_bars ; cin >> one_weight ; This code prompts the user to enter data then reads two data items from cin The first value read is stored in number_of_bars The second value read is stored in one_weight Data is separated by spaces when entered Slide 2- 80
Reading Data From cin Multiple data items are separated by spaces Data is not read until the enter key is pressed Allows user to make corrections Example: cin >> v1 >> v2 >> v3; Requires three space separated values User might type 34 45 12 <enter key> Slide 2- 81
Knowledge Check Write the C++ statement to display Write the C++ statement to display Write the C++ statement to display Write the C++ statement to read 3 integer inputs from the user hello world hello there, isn’t it a good day. will you get an “A+” in TCP1121?
1.6 Data Types and Expressions
Data Types and Expressions 2 and 2.0 are not the same number A whole number such as 2 is of type int A real number such as 2.0 is of type double Numbers of type int are stored as exact values Numbers of type double may be stored as approximate values due to limitations on number of significant digits that can be represented Slide 2- 84
Writing Integer constants Type int does not contain decimal points Examples: 34 45 1 89 Slide 2- 85
Writing Double Constants Type double can be written in two ways Simple form must include a decimal point Examples: 34.1 23.0034 1.0 89.9 Floating Point Notation (Scientific Notation) Examples: 3.41e1 means 34.1 3.67e17 means 367000000000000000.0 5.89e-6 means 0.00000589 Number left of e does not require a decimal point Exponent cannot contain a decimal point Slide 2- 86
Other Number Types Various number types have different memory requirements More precision requires more bytes of memory Very large numbers require more bytes of memory Very small numbers require more bytes of memory Slide 2- 87
Slide 2- 88
Type char Computers process character data too char Short for character Can be any single character from the keyboard To declare a variable of type char: char letter; char letter = 'a'; Slide 2- 89
Reading Character Data cin skips blanks and line breaks looking for data The following reads two characters but skips any space that might be between char symbol1, symbol2; cin >> symbol1 >> symbol2; User normally separate data items by spaces J D Results are the same if the data is not separated by spaces JD Slide 2- 90
Slide 2- 91
Type string string is a class, different from the primitive data types discussed so far Use double quotes around the text to store into the string variable To declare a variable of type string: string name = “Mary Michelle"; Slide 2- 92
Slide 2- 93
Type Compatibilities In general store values in variables of the same type This is a type mismatch: int int_variable ; int_variable = 2.99; If your compiler allows this, int_variable will most likely contain the value 2, not 2.99 Slide 2- 94
int double (part 1) Variables of type double should not be assigned to variables of type int int int_variable ; double double_variable ; double_variable = 2.00; int_variable = double_variable ; If allowed, int_variable contains 2, not 2.00 Slide 2- 95
int double (part 2) Integer values can normally be stored in variables of type double double double_variable; double_variable = 2; double_variable will contain 2.0 Slide 2- 96
char int The following actions are possible but generally not recommended! It is possible to store char values in integer variables int value = 'A'; value will contain an integer representing 'A' It is possible to store int values in char variables char letter = 65; Slide 2- 97
Quick question What is the output and why? char ch1='a', ch2='A'; int lower = ch1, upper = ch2; if( lower == upper ) cout << "Same ASCII value\n"; else cout << "Different ASCII value\n"; Slide 1- 98
bool int The following actions are possible but generally not recommended! Values of type bool can be assigned to int variables True is stored as 1 False is stored as 0 Values of type int can be assigned to bool variables Any non-zero integer is stored as true Zero is stored as false Slide 2- 99
Arithmetic Arithmetic is performed with operators + for addition - for subtraction * for multiplication / for division Example: storing a product in the variable total_weight total_weight = one_weight * number_of_bars; Slide 2- 100
Results of Operators Arithmetic operators can be used with any numeric type An operand is a number or variable used by the operator Result of an operator depends on the types of operands If both operands are int , the result is int If one or both operands are double, the result is double Slide 2- 101
Division of Doubles Division with at least one operator of type double produces the expected results. double divisor, dividend, quotient; divisor = 3; dividend = 5; quotient = dividend / divisor; quotient = 1.6666… What is the result if either dividend or divisor is of type int ? Slide 2- 102
Quick question Evaluate the below snippet int x = 10, y = 4; float result; result = x / y; cout << result << endl ; Slide 1- 103
How to remedy it? int x = 10, y = 4; float result; result = (float) x / y; cout << result << endl; Slide 1- 104
Integer Remainders % operator gives the remainder from integer division int dividend, divisor, remainder; dividend = 5; divisor = 3; remainder = dividend % divisor; The value of remainder is 2 Slide 2- 105
Arithmetic Expressions Use spacing to make expressions readable Which is easier to read? x+y *z or x + y * z Precedence rules for operators are the same as used in your algebra classes Use parentheses to alter the order of operations x + y * z ( y is multiplied by z first) (x + y) * z ( x and y are added first) Slide 2- 106
Slide 2- 107
Operator Shorthand Some expressions occur so often that C++ contains to shorthand operators for them All arithmetic operators can be used this way += count = count + 2; becomes count += 2; *= bonus = bonus * 2; becomes bonus *= 2; /= time = time / rush_factor ; becomes time /= rush_factor ; %= remainder = remainder % (cnt1+ cnt2); becomes remainder %= (cnt1 + cnt2); Slide 2- 108
Lecture 2 C++ Fundamentals 2.1 Flow of Control 2.2 Scope and Local Variables
2.1 Flow of Control
Simple Flow of Control Flow of control The order in which statements are executed Branch Lets program choose between two alternatives Slide 2- 111
Branch Example To calculate hourly wages there are two choices Regular time ( up to 40 hours) gross_pay = rate * hours; Overtime ( over 40 hours) gross_pay = rate * 40 + 1.5 * rate * (hours - 40); The program must choose which of these expressions to use Slide 2- 112
Designing the Branch Decide if (hours >40) is true If it is true, then use gross_pay = rate * 40 + 1.5 * rate * (hours - 40); If it is not true, then use gross_pay = rate * hours; Slide 2- 113
Implementing the Branch if-else statement is used in C++ to perform a branch if (hours > 40) gross_pay = rate * 40 + 1.5 * rate * (hours - 40); else gross_pay = rate * hours; Slide 2- 114
Boolean Expressions Boolean expressions are expressions that are either true or false comparison operators such as '>' (greater than) are used to compare variables and/or numbers (hours > 40) Including the parentheses, is the boolean expression from the wages example A few of the comparison operators that use two symbols (No spaces allowed between the symbols!) >= greater than or equal to != not equal or inequality = = equal or equivalent Slide 2- 115
Slide 2- 116
if-else Flow Control if ( boolean expression) true statement else false statement When the boolean expression is true Only the true statement is executed When the boolean expression is false Only the false statement is executed Slide 2- 117
AND Boolean expressions can be combined into more complex expressions with && -- The AND operator True if both expressions are true Syntax: (Comparison_1) && (Comparison_2) Example: if ( (2 < x) && (x < 7) ) True only if x is between 2 and 7 Inside parentheses are optional but enhance meaning Slide 2- 118
OR | | -- The OR operator (no space!) True if either or both expressions are true Syntax: (Comparison_1) | | (Comparison_2) Example: if ( ( x = = 1) | | ( x = = y) ) True if x contains 1 True if x contains the same value as y True if both comparisons are true Slide 2- 119
NOT ! -- negates any boolean expression !( x < y) True if x is NOT less than y !(x = = y) True if x is NOT equal to y ! Operator can make expressions difficult to understand…use only when appropriate Slide 2- 120
Inequalities Be careful translating inequalities to C++ if x < y < z translates as if ( ( x < y ) && ( y < z ) ) NOT if ( x < y < z ) Slide 2- 121
Pitfall: Using = or == ' = ' is the assignment operator Used to assign values to variables Example: x = 3; '= = ' is the equality operator Used to compare values Example: if ( x == 3) The compiler will accept this error: if (x = 3) but stores 3 in x instead of comparing x and 3 Since the result is 3 (non-zero), the expression is true Slide 2- 122
Compound Statements A compound statement is more than one statement enclosed in { } Branches of if-else statements often need to execute more that one statement Example: if ( boolean expression) { true statements } else { false statements } Slide 2- 123
Slide 2- 124
Using Boolean Expressions A Boolean Expression is an expression that is either true or false Boolean expressions are evaluated using relational operations such as = = , < , and >= which produce a boolean value and boolean operations such as &&, | |, and ! which also produce a boolean value Type bool allows declaration of variables that carry the value true or false Slide 3- 125
Evaluating Boolean Expressions Boolean expressions are evaluated using values from the Truth Tables in For example, if y is 8, the expression !( ( y < 3) | | ( y > 7) ) is evaluated in the following sequence Slide 3- 126 ! ( false | | true ) ! ( true ) false
Slide 3- 127
Order of Precedence If parenthesis are omitted from boolean expressions, the default precedence of operations is: Perform ! operations first Perform relational operations such as < next Perform && operations next Perform | | operations last Slide 3- 128
Slide 3- 129
Precedence Rule Example The expression (x+1) > 2 | | (x + 1) < -3 is equivalent to ( (x + 1) > 2) | | ( ( x + 1) < -3) Because > and < have higher precedence than | | and is also equivalent to x + 1 > 2 | | x + 1 < - 3 Slide 3- 130 First apply the unary – Next apply the +'s Now apply the > and < Finally do the | |
Problems with ! The expression ( ! time > limit ), with limit = 60, is evaluated as (!time) > limit If time is an int with value 36, what is !time? False! Or zero since it will be compared to an integer The expression is further evaluated as 0 > limit false Slide 3- 131
Correcting the ! Problem The intent of the previous expression was most likely the expression ( ! ( time > limit) ) which evaluates as ( ! ( false) ) true Slide 3- 132
Avoiding ! Just as not in English can make things not undifficult to read, the ! operator can make C++ expressions difficult to understand Before using the ! operator see if you can express the same idea more clearly without the ! operator Slide 3- 133
Enumeration Types (Optional) An enumeration type is a type with values defined by a list of constants of type int Example: enum MonthLength{JAN_LENGTH = 31, FEB_LENGTH = 28, MAR_LENGTH = 31, … DEC_LENGTH = 31}; Slide 3- 134
enum Values If numeric values are not specified, identifiers are assigned consecutive values starting with 0 enum Direction { NORTH = 0, SOUTH = 1, EAST = 2, WEST = 3}; is equivalent to enum Direction {NORTH, SOUTH, EAST, WEST}; Unless specified, the value assigned an enumeration constant is 1 more than the previous constant enum MyEnum {ONE = 17, TWO, THREE, FOUR = -3, FIVE}; results in these values ONE = 17, TWO = 18, THREE = 19, FOUR = -3, FIVE = -2 Slide 3- 135
Nested Statements A statement that is a subpart of another statement is a nested statement When writing nested statements it is normal to indent each level of nesting Example: if (count < 10) if ( x < y) cout << x << " is less than " << y; else cout << y << " is less than " << x; Slide 3- 136 indented
Slide 3- 137
Nested if-else Statements Use care in nesting if-else-statements Example: To design an if-else statement to warn a driver when fuel is low, but tells the driver to bypass pit stops if the fuel is close to full. Other wise there should be no output. Pseudocode: if fuel gauge is below ¾ then: if fuel gauge is below ¼ then: issue a warning otherwise (gauge > ¾) then: output a statement saying don't stop Slide 3- 138
First Try Nested if's Translating the previous pseudocode to C++ could yield (if we are not careful) if (fuel_gauge_reading < 0.75) if (fuel_gauge_reading < 0.25) cout << "Fuel very low. Caution!\n"; else cout << "Fuel over 3/4. Don't stop now!\n"; This would compile and run, but does not produce the desired results The compiler pairs the "else" with the nearest previous "if" Slide 3- 139
Braces and Nested Statements Braces in nested statements are like parenthesis in arithmetic expressions Braces tell the compiler how to group things Use braces around substatements demonstrates the use of braces in nested if-else-statements Slide 3- 140
Slide 3- 141
Multi-way if-else-statements An if-else-statement is a two-way branch Three or four (or more) way branches can be designed using nested if-else-statements Example: The number guessing game with the number stored in variable number, the guess in variable guess. How do we give hints? Slide 3- 142
Number Guessing The following nested statements implement the hints for our number guessing game if (guess> number) cout << "Too high."; else if (guess < number) cout << "Too low."); else if (guess == number) cout << "Correct!"; Slide 3- 143
Indenting Nested if-else Notice how the code on the previous slide crept across the page leaving less and less space Use this alternative for indenting several nested if-else-statements: if (guess> number) cout << "Too high."; else if (guess < number) cout << "Too low."); else if (guess == number) cout << "Correct!"; Slide 3- 144
The Final if-else-statement When the conditions tested in an if-else-statement are mutually exclusive, the final if-else can sometimes be omitted. The previous example can be written as if (guess> number) cout << "Too high."; else if (guess < number) cout << "Too low."); else // (guess == number) cout << "Correct!"; Slide 3- 145
Program Example: State Income Tax Write a program for a state that computes tax according to the rate schedule: No tax on first $15,000 of income 5% tax on each dollar from $15,001 to $25,000 10% tax on each dollar over $25,000 Slide 3- 146
Slide 3- 147
Refining if-else-statements Notice that the line else if (( net_income > 15000 && net_income < = 25000)) can be replaced with else if (net_income <= 25000) The computer will not get to this line unless it is already determined that net_income > 15000 Slide 3- 148
The switch-statement The switch-statement is an alternative for constructing multi-way branches The following example determines output based on a letter grade Grades 'A', 'B', and 'C' each have a branch Grades 'D' and 'F' use the same branch If an invalid grade is entered, a default branch is used Slide 3- 149
Slide 3- 150
Slide 3- 151
switch-statement Syntax switch (controlling expression) { case Constant_1: statement_Sequence_1 break; case Constant_2: Statement_Sequence_2 break; . . . case Constant_n: Statement_Sequence_n break; default: Default_Statement_Sequence } Slide 3- 152
The Controlling Statement A switch statement's controlling statement must return one of these types A bool value An enum constant An integer type A character The value returned is compared to the constant values after each "case" When a match is found, the code for that case is used Slide 3- 153
The break Statement The break statement ends the switch-statement Omitting the break statement will cause the code for the next case to be executed! Omitting a break statement allows the use of multiple case labels for a section of code case 'A': case 'a': cout << "Excellent."; break; Runs the same code for either 'A' or 'a' Slide 3- 154
The default Statement If no case label has a constant that matches the controlling expression, the statements following the default label are executed If there is no default label, nothing happens when the switch statement is executed It is a good idea to include a default section Slide 3- 155
Switch-statements and Menus Nested if-else statements are more versatile than a switch statement Switch-statements can make some code more clear A menu is a natural application for a switch-statement Slide 3- 156
Slide 3- 157
Slide 3- 158
Function Calls in Branches Switch and if-else-statements allow the use of multiple statements in a branch Multiple statements in a branch can make the switch or if-else-statement difficult to read Using function calls (as shown in previous example) instead of multiple statements can make the switch or if-else-statement much easier to read Slide 3- 159
Blocks Each branch of a switch or if-else statement is a separate sub-task If the action of a branch is too simple to warrant a function call, use multiple statements between braces A block is a section of code enclosed by braces Variables declared within a block, are local to the block or have the block as their scope. Variable names declared in the block can be reused outside the block Slide 3- 160
Slide 3- 161
Slide 3- 162
Scope Rule for Nested Blocks If a single identifier is declared as a variable in each of two blocks, one within the other, then these are two different variables with the same name One of the variables exists only within the inner block and cannot be accessed outside the inner block The other variable exists only in the outer block and cannot be accessed in the inner block Slide 3- 163
Knowledge Check Can you Give the output of this code fragment? { int x = 1; cout << x << endl ; { cout << x << endl ; int x = 2; cout << x << endl ; } cout << x << endl ; Slide 3- 164
Simple Loops When an action must be repeated, a loop is used C++ includes several ways to create loops We start with the while-loop Example: while ( count_down > 0) { cout << "Hello "; count_down -= 1; } Output: Hello Hello Hello when count_down starts at 3 Slide 2- 165
Slide 2- 166
While Loop Operation First, the boolean expression is evaluated If false, the program skips to the line following the while loop If true, the body of the loop is executed During execution, some item from the boolean expression is changed After executing the loop body, the boolean expression is checked again repeating the process until the expression becomes false A while loop might not execute at all if the boolean expression is false on the first check Slide 2- 167
while Loop Syntax while ( boolean expression is true) { statements to repeat } Semi-colons are used only to end the statements within the loop While ( boolean expression is true) statement to repeat Slide 2- 168
do-while loop A variation of the while loop. A do-while loop is always executed at least once The body of the loop is first executed The boolean expression is checked after the body has been executed Syntax: do { statements to repeat } while (boolean_expression); Slide 2- 169
Slide 2- 170
Increment/Decrement Unary operators require only one operand + in front of a number such as +5 - in front of a number such as -5 ++ increment operator Adds 1 to the value of a variable x ++; is equivalent to x = x + 1; -- decrement operator Subtracts 1 from the value of a variable x --; is equivalent to x = x – 1; Slide 2- 171
Sample Program Bank charge card balance of $50 2% per month interest How many months without payments before your balance exceeds $100 After 1 month: $50 + 2% of $50 = $51 After 2 months: $51 + 2% of $51 = $52.02 After 3 months: $52.02 + 2% of $52.02 … Slide 2- 172
Slide 2- 173
Infinite Loops Loops that never stop are infinite loops The loop body should contain a line that will eventually cause the boolean expression to become false Example: Print the odd numbers less than 12 x = 1; while (x != 12) { cout << x << endl ; x = x + 2; } Better to use this comparison: while ( x < 12) Slide 2- 174
Knowledge Check Can you Show the output of this code if x is of type int ? x = 10; while ( x > 0) { cout << x << endl ; x = x – 3; } Show the output of the previous code using the comparison x < 0 instead of x > 0? Slide 2- 175
More About C++ Loop Statements A loop is a program construction that repeats a statement or sequence of statements a number of times The body of the loop is the statement(s) repeated Each repetition of the loop is an iteration Loop design questions: What should the loop body be? How many times should the body be iterated? Slide 3- 176
while and do-while An important difference between while and do-while loops: A while loop checks the Boolean expression at the beginning of the loop A while loop might never be executed! A do-while loop checks the Boolean expression at the end of the loop A do-while loop is always executed at least once Review while and do-while syntax in Slide 3- 177
Slide 3- 178
The Increment Operator We have used the increment operator in statements such as number++; to increase the value of number by one The increment operator can also be used in expressions: int number = 2; int value_produced = 2 * (number++); (number++) first returns the value of number (2) to be multiplied by 2, then increments number to three Slide 3- 179
number++ vs ++number (number++) returns the current value of number, then increments number An expression using (number++) will use the value of number BEFORE it is incremented (++number) increments number first and returns the new value of number An expression using (++number) will use the value of number AFTER it is incremented Number has the same value after either version! Slide 3- 180
++ Comparisons int number = 2; int value_produced = 2 * (number++); cout << value_produced << " " << number; displays 4 3 int number = 2; int value_produced = 2* (++number); cout << value_produced << " " number; displays 6 3 Slide 3- 181
Slide 3- 182
The Decrement Operator The decrement operator (--) decreases the value of the variable by one int number = 8; int value_produced = number--; cout << value_produced << " " << number; displays 8 7 Replacing "number--" with "--number" displays 7 7 Slide 3- 183
The for-Statement A for-Statement (for-loop) is another loop mechanism in C++ Designed for common tasks such as adding numbers in a given range Is sometimes more convenient to use than a while loop Does not do anything a while loop cannot do Slide 3- 184
for/while Loop Comparison sum = 0; n = 1; while(n <= 10) // add the numbers 1 - 10 { sum = sum + n; n++; } sum = 0; for (n = 1; n <= 10; n++) //add the numbers 1 - 10 sum = sum + n; Slide 3- 185
For Loop Dissection The for loop uses the same components as the while loop in a more compact form for (n = 1; n <= 10; n++) Slide 3- 186 Initialization Action Boolean Expression Update Action
for Loop A for loop can also include a variable declaration in the initialization action for ( int n = 1; n < = 10; n++) This line means Create a variable, n, of type int and initialize it with 1 Continue to iterate the body as long as n <= 10 Increment n by one after each iteration Here are some samples for (n = 1; n < = 10; n = n + 2) for(n = 0 ; n > -100 ; n = n -7) for(double x = pow(y,3.0); x > 2.0; x = sqrt (x) ) Slide 3- 187
Slide 3- 188
The for-loop Body The body of a for-loop can be A single statement A compound statement enclosed in braces Example: for(int number = 1; number >= 0; number--) { // loop body statements } shows the syntax for a for-loop with a multi-statement body Slide 3- 189
Slide 3- 190
The Empty Statement A semicolon creates a C++ statement Placing a semicolon after x++ creates the statement x++; Placing a semicolon after nothing creates an empty statement that compiles but does nothing cout << "Hello" << endl; ; cout << "Good Bye"<< endl; Slide 3- 191
Extra Semicolon Placing a semicolon after the parentheses of a for loop creates an empty statement as the body of the loop Example: for(int count = 1; count <= 10; count++); cout << "Hello\n"; prints one "Hello", but not as part of the loop! The empty statement is the body of the loop cout << "Hello\n"; is not part of the loop body! Slide 3- 192
Local Variable Standard ANSI C++ standard requires that a variable declared in the for-loop initialization section be local to the block of the for-loop Find out how your compiler treats these variables! If you want your code to be portable, do not depend on all compilers to treat these variables as local to the for-loop! Slide 3- 193
Which Loop To Use? Choose the type of loop late in the design process First design the loop using pseudocode Translate the pseudocode into C++ The translation generally makes the choice of an appropriate loop clear While-loops are used for all other loops when there might be occassions when the loop should not run Do-while loops are used for all other loops when the loop must always run at least once Slide 3- 194
Choosing a for-loop for-loops are typically selected when doing numeric calculations, especially when using a variable changed by equal amounts each time the loop iterates Slide 3- 195
Choosing a while-loop A while-loop is typically used When a for-loop is not appropriate When there are circumstances for which the loop body should not be executed at all Slide 3- 196
Choosing a do-while Loop A do-while-loop is typically used When a for-loop is not appropriate When the loop body must be executed at least once Slide 3- 197
The break-Statement There are times to exit a loop before it ends If the loop checks for invalid input that would ruin a calculation, it is often best to end the loop The break-statement can be used to exit a loop before normal termination Be careful with nested loops! Using break only exits the loop in which the break-statement occurs Slide 3- 198
Slide 3- 199
Knowledge Check Can you Determine the output of the following? for(int count = 1; count < 5; count++) cout << (2 * count) << " " ; Determine which type of loop is likely to be best for Summing a series such as 1/2 + 1/3 + 1/4 + … + 1/10? Reading a list of exam scores for one student? Testing a function to see how it performs with different values of its arguments Slide 3- 200
Sums and Products A common task is reading a list of numbers and computing the sum Pseudocode for this task might be: sum = 0; repeat the following this_many times cin >> next; sum = sum + next; end of loop This pseudocode can be implemented with a for-loop as shown on the next slide Slide 3- 201
for-loop for a sum The pseudocode from the previous slide is implemented as int sum = 0; for(int count=1; count <= this_many; count++) { cin >> next; sum = sum + next; } sum must be initialized prior to the loop body! Slide 3- 202
Repeat "this many times" Pseudocode containing the line repeat the following "this many times" is often implemented with a for-loop A for-loop is generally the choice when there is a predetermined number of iterations Example: for(int count = 1; count <= this_many; count++) Loop_body Slide 3- 203
for-loop For a Product Forming a product is very similar to the sum example seen earlier int product = 1; for(int count=1; count <= this_many; count++) { cin >> next; product = product * next; } product must be initialized prior to the loop body Notice that product is initialized to 1, not 0! Slide 3- 204
Ending a Loop The are four common methods to terminate an input loop List headed by size When we can determine the size of the list beforehand Ask before iterating Ask if the user wants to continue before each iteration List ended with a sentinel value Using a particular value to signal the end of the list Running out of input Using the eof function to indicate the end of a file Slide 3- 205
List Headed By Size The for-loops we have seen provide a natural implementation of the list headed by size method of ending a loop Example: int items; cout << "How many items in the list?"; cin >> items; for(int count = 1; count <= items; count++) { int number; cout << "Enter number " << count; cin >> number; cout << endl; // statements to process the number } Slide 3- 206
Ask Before Iterating A while loop is used here to implement the ask before iterating method to end a loop sum = 0; cout << "Are there numbers in the list (Y/N)?"; char ans; cin >> ans; while (( ans = 'Y') || (ans = 'y')) { //statements to read and process the number cout << "Are there more numbers(Y/N)? "; cin >> ans; } Slide 3- 207
List Ended With a Sentinel Value A while loop is typically used to end a loop using the list ended with a sentinel value method cout << "Enter a list of nonnegative integers.\n" << "Place a negative integer after the list.\n"; sum = 0; cin >> number; while (number > 0) { //statements to process the number cin >> number; } Notice that the sentinel value is read, but not processed Slide 3- 208
Running Out of Input The while loop is typically used to implement the running out of input method of ending a loop ifstream infile; infile.open("data.dat"); while (! infile.eof( ) ) { // read and process items from the file // File I/O covered in Chapter 6 } infile.close( ); Slide 3- 209
General Methods To Control Loops Three general methods to control any loop Count controlled loops Ask before iterating Exit on flag condition Slide 3- 210
Count Controlled Loops Count controlled loops are loops that determine the number of iterations before the loop begins The list headed by size is an example of a count controlled loop for input Slide 3- 211
Exit on Flag Condition Loops can be ended when a particular flag condition exists A variable that changes value to indicate that some event has taken place is a flag Examples of exit on a flag condition for input List ended with a sentinel value Running out of input Slide 3- 212
Exit on Flag Caution Consider this loop to identify a student with a grade of 90 or better int n = 1; grade = compute_grade (n); while (grade < 90) { n++; grade = compute_grade (n); } cout << "Student number " << n << " has a score of " << grade << endl ; Slide 3- 213
The Problem The loop on the previous slide might not stop at the end of the list of students if no student has a grade of 90 or higher It is a good idea to use a second flag to ensure that there are still students to consider The code on the following slide shows a better solution Slide 3- 214
The Exit On Flag Solution This code solves the problem of having no student grade at 90 or higher int n=1; grade = compute_grade (n); while (( grade < 90) && ( n < number_of_students )) { // same as before } if (grade > 90) // same output as before else cout << "No student has a high score."; Slide 3- 215
Nested Loops The body of a loop may contain any kind of statement, including another loop When loops are nested, all iterations of the inner loop are executed for each iteration of the outer loop Give serious consideration to making the inner loop a function call to make it easier to read your program The following example shows two versions of a program with nested loops Slide 3- 216
Slide 3- 217
Knowledge Check Both questions should be done using all THREE (3) types of loop; for, while, do-while. Write a program to calculate the sum of 10 marks inputted by the user. Write a program to continuously get a user inputted number until the user keys in 0. After getting the number, display ODD / EVEN depending on the input. Slide 1- 218
2.2 Scope and Local Variables
Local Variables Variables declared in a function: Are local to that function, they cannot be used from outside the function Have the function as their scope Variables declared in the main part of a program: Are local to the main part of the program, they cannot be used from outside the main part Have the main part as their scope Slide 4- 220
Slide 4- 221
Slide 4- 222
Global Constants Global Named Constant Available to more than one function as well as the main part of the program Declared outside any function body Declared outside the main function body Declared before any function that uses it Example: const double PI = 3.14159; double volume(double); int main() {…} PI is available to the main function and to function volume Slide 4- 223
Slide 4- 224
Slide 4- 225
Global Variables Global Variable -- rarely used when more than one function must use a common variable Declared just like a global constant except const is not used Generally make programs more difficult to understand and maintain Slide 4- 226
Block Scope Local and global variables conform to the rules of Block Scope The code block (generally defined by the { }) where an identifier like a variable is declared determines the scope of the identifier Blocks can be nested Slide 1- 227
Slide 4- 228
Knowledge Check Differentiate between local and global variables. Provide an example each. Write the C++ statement to declare a constant variable called modifier with the value 1.7. Can constant variables be reassigned with another value? Can you create a local constant or must it always be global scope?
C++ Fundamentals -- End Slide 2- 230 Slides adapted from Walter Savitch , “Problem solving with C++”