Lec01-02 (Topic 1 C++ Fundamentals) - v2
Lec01-02 (Topic 1 C++ Fundamentals) - v2
C++ Fundamentals
 4
My first program in C++ Hello World!
a comment line
 int main()
 {
 variable_declarations
 statement_1
 statement_2
 …
 statement_last
 return 0;
 }
 6
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;
}
 7
 Program Layout
using namespace std;
 ▪ Tells the compiler to use names in iostream in a
 “standard” way
 9
 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
 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.
 18
 Implementation Phase
5, 10 15
 1. Pseudo code
 2. Structure diagram
 3. Flowcharts
 21
 Pseudocode
 22
 Pseudocode
Write a program calculating the sum of two numbers
 Version 1:
 PROGRAM Add Two Numbers
 READ two numbers
 ADD the numbers
 WRITE the sum
 END PROGRAM
 Version 2:
 PROGRAM Add Two Numbers
 READ First
 READ Second
 COMPUTE Sum = First + Second
 WRITE Sum
 END PROGRAM
 23
 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
 25
 Structure Diagram
 Version 2: PROGRAM
 Add Two Numbers
 26
 Rules for Structure Diagram
 27
 Flowchart
 28
Flowchart Symbols
 • Start/End terminal (used to indicate the beginning and end of a
 program or module)
• 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
• 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
All flowchart symbols are joined by the directional
arrow. Without a direction, we cannot see the flow in
the flowchart.
Common mistakes:
 1. Not labelling output paths of a decision
 2. Not writing a question in the decision symbol
 3. Connecting the flowchart using lines instead of arrows
Write a program calculating the sum of two numbers
 START
 READ First
 READ Second
WRITE Sum
END
 38
 Flowchart Conventions
1) Each symbol denotes a type of operation.
2) A note is written inside each symbol to indicate the specific
 function to be performed.
3) The symbols are connected by flow-lines.
4) Flowcharts are drawn and read from top to bottom unless a
 specific condition is met that alters the path.
5) A sequence of operations is performed until a terminal
 symbol designates the sequence's end or the end of the
 program.
6) Sometimes several steps or statements are combined in a
 single processing symbol for ease of reading.
 39
 start
A flowchart to accepts two numbers as
input and prints out the maximum
 Input A
Input B
 False True
 A>B
print B print A
end
 40
 Structured Programming
 41
 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.
True
 False
 Different selection structures
1) If a > 10 then do S1 2) If a > 10 then do nothing else do S2
 false true
 true false A>10
 A>10
S1 S2
 True False
 true false
 A>10 A<=10
S1 S2 S1
 45
 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… Case
 CASE
 grade
 If grade is:
 A B C D
 A, do S1
 B, do S2
 S1 S2 S3 S4
 C, do S3
 D, do S4
 Different selection structures… cont
• Another way to represent switch…case
If the grade is: grade = “A” S1 break
 A, do S1
 B, do S2
 grade = “B” S2 break
 C, do S3
 D, do S4
 grade = “C” S3 break
 A< true
 =10 S2
 False
Repeat While A is less than or equal to
S1 10 repeat
S2 S1
 C=1
2 Sum False
 =0 3 c<=
 5
 4 5 6
 true
3
 C=1 C=1 C=1 C=2
 Sum = 0 Sum Sum Sum 4 Input A
 C <=5 =3 =3 =3
 true A=3 A=3 A=3
 5 Sum = Sum + A
 C=2
 Sum = 3
 C=2
 Sum
 C=2
 Sum
 C=3
 Sum
 6 C=C+1
 C <=5 =3 =5 =5
 true A=2 A=2 A=3
 Output
 3 4 5 6 7 Sum
 End 50
 Prime number example flowchart
 Start 1
Pseudocode algorithm to solve
 this problem: Input 2
 M
1. Start 3
 I=2
2. Input a number M
3. Set an Index (I) to start from 2
4. Divide the number M by the Index (I) R=M%I 4
 value and store the remainder in R True
 False R=0
5. If R is equal to zero then output “Not ? 5
 Prime” and goto to Step 10
6. Increment Index (I) by 1 I=I+1 6
7. If the Index (I) value is less than the True
 I<M 7
 number M go to Step 4 ?
8. Output “Prime” False
9. End Output Output 8
 Prime Not Prime
 End 9
 51
 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
o Bug
 o A mistake in a program
o Debugging
 o Eliminating mistakes in programs
 o 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:
 Slide 1- 54
 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- 55
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- 57
 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- 58
 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- 59
 Declaring Variables (Part 1)
• Before use, variables must be declared
 Slide 2- 61
 Declaring Variables (Part 3)
• Declaration syntax:
 – Type_name Variable_1 , Variable_2, . . . ;
• Declaration Examples:
 – double average, m_score, total_score;
 – double moon_distance;
 – int age, num_students;
 – int cars_waiting;
 Slide 2- 62
 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
number_of_bars = number_of_bars + 3;
 Slide 2- 64
 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
 Slide 2- 68
 Output using cout
 Slide 2- 69
 Examples Using cout
• This produces the same result as the previous sample
#include <iostream>
 Slide 2- 71
 Escape Sequences
• Escape sequences tell the compiler to treat characters in a special
 way
• Example: cout.setf(ios::fixed);
 cout.setf(ios::showpoint);
 cout.precision(2);
 cout << "The price is " << price <<
 endl;
 Slide 2- 74
 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- 75
 Reading Data From cin
• Multiple data items are separated by spaces
• Data is not read until the enter key is pressed
 – Allows the user to make corrections
• Example:
 cin >> v1 >> v2 >> v3;
 Slide 2- 76
 Knowledge Check
• Write the C++ statement to display
 hello world
 Slide 2- 79
 Writing Integer constants
• Type int does not contain decimal points
• Examples: 34 45 1 89
 Slide 2- 80
 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
 Slide 2- 82
Slide 2- 83
 Type char
• Computers process character data too
• char
 – Short for character
 – Can be any single character from the keyboard
char letter;
 Slide 2- 84
 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
 Slide 2- 87
Slide 2- 88
 Type Boolean
• Values of type Boolean (keyword: bool) can be assigned
 variables as
 – True
 – False
 Slide 2- 89
 Type Compatibilities
• In general store values in variables of the
 same type
 – This is a type mismatch:
 int a;
 a = 2.99;
 Slide 2- 90
 int  double (part 1)
• Variables of type double should not be
 assigned to variables of type int
 int int_var;
 double double_var;
 double_var = 2.00;
 int_var = double_var;
 Slide 2- 91
 int  double (part 2)
• Integer values can normally be stored in
 variables of type double
 double dvar;
 dvar = 2;
 Slide 2- 92
 char int
• The following actions are possible but generally not
 recommended!
 Slide 2- 93
 Quick question
What is the output and why?
 Slide 1- 94
 bool int
• The following actions are possible but generally not
 recommended!
 Slide 2- 95
 Arithmetic
• Arithmetic is performed with operators
 – + for addition
 – - for subtraction
 – * for multiplication
 – / for division
 Slide 2- 96
 Results of Operators
• Arithmetic operators can be used with any
 numeric type
• An operand is a number or variable used by
 the operator
• The 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- 97
 Division of Doubles
• Division with at least one operator of type double produces
 the expected results.
 Slide 2- 98
 Quick question
• Evaluate the below snippet
int x = 10, y = 4;
float result;
result = x / y;
cout << result << endl;
 Slide 1- 99
 How to remedy it?
int x = 10, y = 4;
float result;
result = (float) x / y;
cout << result << endl;
 Slide 1- 100
 Integer Remainders
• % operator gives the remainder from integer division
 Slide 2- 101
 Arithmetic Expressions
• Use spacing to make expressions readable
 – Which is easier to read?
x+y*z or x + y * z
 Slide 2- 102
Slide 2- 103
 Operator Shorthand
• Some expressions occur so often that C++ contains to
 shorthand operators for them
 Slide 2- 104
 Lecture 2
 C++ Fundamentals
2.1 Flow of Control (Selection Structure and Repetition Structure)
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- 107
 Branch Example
• To calculate hourly wages there are two choices
 Slide 2- 108
 Designing the Branch
 Slide 2- 109
 Implementing the Branch
• if-else statement is used in C++ to perform a
 branch
 Slide 2- 110
 Boolean Expressions
• Boolean expressions are expressions that are either true or
 false
• if(boolean expression)
 true statement
 else
 false statement
 Slide 2- 114
 OR
• The OR operator (||) Note: no space between the symbol!
 – True if either or both expressions are true
 Slide 2- 115
 NOT
• The NOT (!) – Negation of Boolean expression
• Syntax: !(BoolExp)
• Example:
 !(x < y)
 • True if x is NOT less than y
 !(x == y)
 • True if x is NOT equal to y
• If time and limit are int with value 36 and 60, what is !
 time?
 – False! Or zero since it will be compared to an integer
 – The expression is further evaluated as
 0 > limit
 0 > 60
 false
 Slide 3- 117
 Correcting the ! Problem
• The intent of the previous expression was
 most likely the expression
 which evaluates as
 ( !(false) )
 true
 Slide 3- 118
 Avoiding !
• Just as not in English can make things not
 undifficult to read, the ! operator can
 make C++ expressions difficult to understand
 Slide 3- 119
 Inequalities
• Be careful translating inequalities to C++
NOT
 if ( x < y < z )
 Slide 2- 120
 Pitfall: Using = or ==
• '=' is the assignment operator
 – Used to assign values to variables
 – Example: x = 3;
 Slide 3- 124
Slide 3- 125
 Precedence Rule Example
• The expression
 (x + 1) > 2 || (x + 1) < -3
 is equivalent to
 ((x + 1) > 2) || (( x + 1) < -3)
 Slide 3- 126
 Increment and Decrement
• Unary operators require only one operand
 – + in front of a number such as +5
 – - in front of a number such as -5
 Slide 2- 127
 The Increment Operator
• We can use the increment operator in statements such as
 number++;
 to increase the value of the variable number by one
 int number = 2;
 int value_produced = 2 * (number++);
• The value of the variable number has the same value after either
 version!
 Slide 3- 129
 ++ Comparisons
• int number = 2;
 int value_produced = 2 * (number++);
 cout << value_produced << " " << number;
Output: 4 3
• int number = 2;
 int value_produced = 2* (++number);
 cout << value_produced << " " number;
Output: 6 3
 Slide 3- 130
 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;
Output: 8 7
 int number = 8;
 int value_produced = --number;
 cout << value_produced << " " << number
 Output: 7 7
 Slide 3- 131
 Selection Structure
(if…else and switch…case)
 IF…ELSE Statements
• Conditional statement that runs a different set of statements
 depending on whether an expression is true or false
 – Example:
 if (count < 10)
 if (x < y)
 cout << x << " is less than "
 << y;
indented else
 cout << y << " is less than "
 << x;
 Slide 3- 135
Slide 3- 136
 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. Otherwise, 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- 137
 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 if the fuel is between 0.25 and 0.75
 – The compiler pairs the "else" with the nearest previous
 "if"
 Slide 3- 138
 Braces and Nested Statements
• Braces in nested statements are like parenthesis in
 arithmetic expressions
 – Braces tell the compiler how to group things
 Slide 3- 139
Slide 3- 140
 Multi-way if…else statements
• An if-else-statement is a two-way branch
 Slide 3- 141
 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- 142
 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- 143
 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 if (guess == number)
 cout << "Correct!";
 Slide 3- 144
 Program Example: State Income Tax
• Write a program for a state that computes tax according to
 the rate schedule:
 Slide 3- 145
Slide 3- 146
 Refining if…else statements
• Notice that the line
else if((net_income > 15000 && net_income < = 25000))
 Slide 3- 147
 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- 148
Slide 3- 149
Slide 3- 150
 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- 151
 The Controlling Statement
• A switch statement's controlling statement must return one
 of these types
 – A bool value
 – An enum constant
 – An int type
 – A char type
 Slide 3- 152
 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;
 Slide 3- 153
 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- 154
Example: Switch-statements and Menus
 Slide 3- 155
Slide 3- 156
Slide 3- 157
 Repetition Structure
(while, do…while, for loop)
 Loops Statements (Repetition)
• When an action must be repeated, a loop is used
 Slide 2- 160
 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 items 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
 Slide 2- 161
Slide 2- 162
 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 of do…while loop: do…while loop has a
 semicolon here!!
 do
 {
 statements to repeat
 }while (boolean_expression);
 ……
 statements after the loop
 …… Slide 2- 163
Slide 2- 164
 Difference between while and do…while
 Slide 3- 165
Slide 3- 166
 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- 167
 for Loop Dissection
• The for loop uses the same components as
 the while loop in a more compact form
 Slide 3- 168
 for Loop
• A for loop can also include a variable declaration in the initialization
 action
 for (int n = 1; n < = 10; n++)
 – Some samples:
 for (n = 1; n < = 10; n = n + 2)
• For loop
 sum = 0;
 for (n = 1; n<=10; n++) //add numbers 1-10
 sum = sum + n;
 Slide 3- 171
Slide 3- 172
 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
 Slide 3- 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;
 }
 Slide 2- 175
 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- 176
Slide 2- 177
 Which Loop To Use?
• Choose the type of loop 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
 – Example:
 – While loops are used for all other loops when there might be
 occasions 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- 178
 Choosing a for loop
 Slide 3- 179
 Choosing a while loop
 Slide 3- 180
 Choosing a do…while Loop
 Slide 3- 181
 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
 Slide 3- 182
Slide 3- 183
 Knowledge Check
• Can you
 – Determine the output of the following?
 for(int count = 1; count < 5; count++)
 cout << (2 * count) << " " ;
 Slide 3- 184
 for loop for a sum
• A common task is reading a list of numbers and
 computing the sum
 Slide 3- 185
 for loop For a Product
• Forming a product is very similar to the sum example
 seen earlier
 int product = 1, maxCount= 5, next;
 for(int count=1; count <= maxCount; count++)
 {
 cin >> next;
 product = product * next;
 }
 Slide 3- 186
 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- 187
 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- 188
 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;
 Slide 3- 189
 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
 Slide 3- 190
 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- 191
General Methods To Control Loops
• Three general methods to control any loop
 Slide 3- 192
 Count Controlled Loops
• Count-controlled loops are loops that
 determine the number of iterations before the
 loop begins
 Slide 3- 193
 Exit on Flag Condition
• Loops can be ended when a particular flag
 condition exists
 – A variable that changes the value to indicate that
 some event has taken place is a flag
 Slide 3- 194
 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); // get grade
 cout << "Student number " << n << " has a score of
 " << grade << endl;
 Slide 3- 195
 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- 196
 The Exit On Flag Solution
• This code solves the problem of having no student grade at 90 or higher
 Slide 1- 198
2.2 Scope and Local Variables
 Scope Rule
• Scope: region of a program where a particular identifier, such
 as a variable, is visible and can be accessed within a specific
 block.
 Slide 3- 200
 Local Scope Variables
• Variable defined within a specific block or function.
• Limited to the scope in which they are declared.
• Memory is allocated when the block or function is entered
 and deallocated when it is exited.
 Slide 4- 201
 Example of Local variables
#include <iostream> Variable x
using namespace std; accessible only in
 main() function
int main(){
 int x = 1;
 cout << x << endl;
 {
 cout << x << endl; The declaration variable x
 int x = 2; only accessible in the inner
 block
 cout << x << endl;
 }
 cout << x << endl;
 return 0;
}
 return 0;
}
• Example:
 #include <iostream>
 using namespace std;
 const double PI = 3.14159;
 int main(){
 double result, radius = 5;
 result = 2 * PI * radius;
 cout << “Circumference of a circle = “ << result;
 }
 – PI is a global constant variable while result and radius
 are local variables to main() function.
 – The PI value cannot be changed. Slide 4- 206
Slide 4- 207
Slide 4- 208
 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- 210