0% found this document useful (0 votes)
51 views

Lec01-02 (Topic 1 C++ Fundamentals) - v2

The document provides an overview of C++ fundamentals covered in Lecture 1, including: introducing C++ and its origins as an enhancement of C; the basic structure of a C++ program with preprocessor directives, user-defined code, and main function; and basic program layout with comments, variable declarations, and statements. It also discusses modeling algorithms using pseudocode, structure diagrams, and flowcharts prior to implementation in C++.

Uploaded by

huaiencheeng
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Lec01-02 (Topic 1 C++ Fundamentals) - v2

The document provides an overview of C++ fundamentals covered in Lecture 1, including: introducing C++ and its origins as an enhancement of C; the basic structure of a C++ program with preprocessor directives, user-defined code, and main function; and basic program layout with comments, variable declarations, and statements. It also discusses modeling algorithms using pseudocode, structure diagrams, and flowcharts prior to implementation in C++.

Uploaded by

huaiencheeng
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 210

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
Basic C++ structure

• A normal C++ programs has 3 components


1. Preprocessor
2. User defined
3. Main function
1) Preprocessor C++ program
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
My first program in C++ Hello World!

a comment line

a pound sign (#) is a directive for the


preprocessor. It is not executable
// my first program in C++ code but indications for the
compiler.
#include <iostream>

using namespace std; tells the compiler's preprocessor to


include the iostream standard header
int main () file.
{
Corresponds to the beginning of the
cout << "Hello World!"; main function declaration. The main
return 0; function is the point where all C++
programs begin their execution.
}

to terminate a program cout is the standard


5 output stream in C++
Layout of a Simple C++ Program
#include <iostream>
using namespace std;

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

▪ To begin the main function of the program


int main()
{
▪ To end the main function
return 0;
}
▪ Main function ends with a return statement
8
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

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.

• 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.
How the compiler works?
Compilation process
Running a C++ Program
▪ C++ source code is written with a text editor

▪ The compiler on your system converts source code to


object code
▪ Fix any errors the compiler indicates and re-compile the
code

▪ The linker combines all the object code


into an executable program.

▪ Run the program


14
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


1. Problem Solving Phase
• Result is an algorithm that solves the problem
2. Implementation Phase
• Result is the algorithm translated into a programming
language
17
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

18
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
19
Sample problems
Write a program calculating the sum of two numbers
Input Processing Output

5, 10 15

1) Declare variables 3) Process


2) Assign values
input_1 sum = input_1 + input_2
input_1 = 5
input_2
input_2 = 10
sum

The computer (and so C++)


Names for our cells
provides basic arithmetic 20
operations. If the operation
you want to use is not provided,
you
20 have to compose it.
Write a program calculating the sum of two numbers

There are many models supporting the development


of the code. We will see now the same algorithm
expressed as:

1. Pseudo code
2. Structure diagram
3. Flowcharts

21
Pseudocode

▪ Mixture of C++ and ordinary English

▪ Allows us to make our algorithm precise


without worrying about the details of C++
syntax

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

▪ Helpful to break the algorithm into more


manageable pieces
▪ Basic tree diagram that shows modules of the
program
Write a program calculating the sum of two numbers
Version 1: PROGRAM
Add Two Numbers

READ ADD WRITE


Two Numbers Two Numbers The Sum

25
Structure Diagram

Write a program calculating the sum of two numbers

Version 2: PROGRAM
Add Two Numbers

READ ADD WRITE


Two Numbers Two Numbers The Sum

READ READ Sum =


Input_1 Input_2 Input_1 + Input_2

26
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

27
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

28
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
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

Sum = First + 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

▪ 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:
1. Sequence
2. Selection
3. Repetition

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

3) If a > 10 then do S1 else do S2 4) If a <= 10 then do S1

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

grade = “D” S4 break


Repetition (loop) structures
A< False
S1
=10
true
S2
S1

A< true
=10 S2

False
Repeat While A is less than or equal to
S1 10 repeat

S2 S1

As long as A is Less than or equal S2


to 10 otherwise exit the loop End loop

What is the difference ? 48


Loop example (do..While)
Draw a flowchart to allow the input of 5 numbers Start
and display the sum of these numbers
1 C=1
Assume the numbers given to A are
3,2,4,5,6 in order
2 Sum=0
C=1 C=1 C=2
C=1
Sum Sum Sum
Sum
=0 =3 =3
=0
A=3 A=3 A=3 3 Input A
1,2 3 4 5
4 Sum = Sum + A

C=2 C=2 C=2 C=3


Sum = 3 Sum Sum Sum 5 C=C+1
A=3 =3 =5 =5
C <=5 true A=2 A=2 A=2
c<= true
6 3 4 5 6
5
False
C=3 C=3 C=3 C=4
Output
Sum = 5 Sum Sum Sum 7 Sum
A=3 =5 =9 =9
C <=5 true A=4 A=4 A=4
End 49
6 3 4 5
Loop example (while…)
Draw a flowchart to allow the input of Start
5 numbers and displays out the sum
of these numbers
1 C=1

1 C=1 Assume the numbers given to A


are 3,2,4,5,6 in order 2 Sum=0

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:

“First actual case of a bug being found.”

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

– 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)
Two locations for variable declarations
– Immediately prior to use – At the beginning
int main()
int main() {
{ int sum;
… …
int sum; sum = score1 +
sum = score1 + score 2; score2; …
… return 0;
return 0; }
}

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

– 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- 63
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- 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

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 (rarely used)
double mpg(26.3), area(0.0),
volume;
Slide 2- 65
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- 68
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- 69
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- 70
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- 71
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- 72
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- 73
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- 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;

– Requires three space-separated values


– User might type
34 45 12 <enter key>

Slide 2- 76
Knowledge Check
• Write the C++ statement to display
hello world

• Write the C++ statement to display


hello there,
isn’t it a good day.
• Write the C++ statement to display
will you get an “A+” in TCP1121?

• Write the C++ statement to read 3 integer


inputs from the user
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 the number of significant
digits that can be represented

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

– 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- 81
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- 82
Slide 2- 83
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- 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

char symbol1, symbol2;


cin >> symbol1 >> symbol2;

• Users normally separate data items by spaces


J D

• Results are the same if the data is not separated


by spaces
JD
Slide 2- 85
Slide 2- 86
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- 87
Slide 2- 88
Type Boolean
• Values of type Boolean (keyword: bool) can be assigned
variables as
– True
– False

• In some situations, values of type int can be assigned to


bool variables
– Any non-zero integer = True
– Zero = 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;

– If your compiler allows this, a will most likely


contain the value 2, not 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;

– If allowed, int_var contains 2, not 2.00

Slide 2- 91
int  double (part 2)
• Integer values can normally be stored in
variables of type double

double dvar;
dvar = 2;

– dvar will contain 2.0

Slide 2- 92
char int
• The following actions are possible but generally not
recommended!

• It is possible to store char values in int 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- 93
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- 94
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- 95
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 * quantity;

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.

double divisor, dividend, result;


divisor = 3;
dividend = 5;
result = dividend / divisor;

– OUTPUT: result = 1.6666…

– What is the result if either dividend or divisor is


of type int?

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

int dividend, divisor, remainder;


dividend = 5;
divisor = 3;
remainder = dividend % divisor;

The value of the remainder variable is 2

Slide 2- 101
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 those 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- 102
Slide 2- 103
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- 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

– 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- 108
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- 109
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- 110
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 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- 111
Slide 2- 112
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- 113
AND
• Boolean expressions can be combined into more complex
expressions with the AND operator (&&)
• True if both expressions are true

• Syntax: (BoolExp_1) && (BoolExp _2)

• Example: if((x > 2) && (x < 7))


– True only if x is between 2 and 7
– Inside parentheses are optional but enhance meaning

Slide 2- 114
OR
• The OR operator (||) Note: no space between the symbol!
– True if either or both expressions are true

• Syntax: (BoolExp_1) || (BoolExp _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- 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

NOTE: The ! operator can make expressions difficult to understand…


Use only when appropriate!!
Slide 2- 116
Problems with !
• The expression (!time > limit)is evaluated as

(!time) > limit

• 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

( !(time > limit) )

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

• Before using the ! operator see if you can


express the same idea more clearly without
the ! operator

Slide 3- 119
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- 120
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- 121
Evaluating Boolean Expressions
• A Boolean Expression is an expression that is either true or
false

• Boolean expressions are evaluated using values from the Truth


Tables (refer to next slide)

For example, if y is 8, the expression

!(( y < 3) || ( y > 7))

is evaluated in the following sequence


! ( false || true )
! (true)
false Slide 3- 122
Slide 3- 123
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- 124
Slide 3- 125
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 ||


• First apply the unary –
• and is also equivalent to • Next apply the +'s
• Now apply the > and <
x + 1 > 2 || x + 1 < - 3 • Finally do the ||

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

• ++  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- 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

• The increment operator can also be used in expressions:

int number = 2;
int value_produced = 2 * (number++);

(number++) first returns the value of variable number (2) to


be multiplied by 2, then increments the value of the variable
number to 3
Slide 3- 128
number++ vs ++number
• (number++) returns the current value of number, then
increments number
– An expression using (number++) will use the value of the
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 the
number AFTER it is incremented

• 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

• Syntax (IF Statement):


if (boolean expression)
{
true statements
}

• Syntax (IF…ELSE Statement)


if (boolean expression)
{
true statements
}
else
{
false statements
} Slide 2- 133
Slide 2- 134
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;
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

• Use braces around sub-statements

• demonstrates the use of braces in nested if-else-


statements

Slide 3- 139
Slide 3- 140
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- 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:

No tax on the 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- 145
Slide 3- 146
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- 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

• 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- 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;

• Runs the same code for either 'A' or 'a'

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

• 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- 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

• A loop is a program construction that repeats a statement or sequence of


statements several 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?

• C++ includes several ways to create loops


• While loop
• Do…while loop
• for loop
Slide 2- 159
while Loop Syntax
• Syntax of while loop:

while(boolean expression is true)


{
statements to repeat
}
……
statements after the loop
……

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

• A while loop might not execute at all if the Boolean


expression is false on the first check

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

• 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 next slide

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

• Syntax of for loop:


for (int n = 1; n <= 10; n++)
{
……
Initialization Action Update Action
……
} Boolean Expression

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++)

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

– 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- 169
Slide 3- 170
for/while Loop Comparison
• While loop
sum = 0;
n = 1;
while(n <= 10) //add the numbers 1-10
{
sum = sum + n;
n++;
}

• 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

• 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- 173
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!

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;
}

– Show the output of the previous code using the


comparison x < 0 instead of x > 0?

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

• For loops are typically selected when doing


numeric calculations, especially when using
a variable changed by equal amounts each
time the loop iterates
• A for loop is generally the choice when there
is a predetermined number of iterations

Slide 3- 179
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- 180
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- 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

• 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- 182
Slide 3- 183
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- 184
for loop for a sum
• A common task is reading a list of numbers and
computing the sum

int sum = 0, maxCount= 5, next;


for(int count = 1; count <= maxCount; count++)
{
cin >> next;
sum = sum + next;
}

– sum must be initialized before the loop body!

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;
}

– product must be initialized before the loop body


– Notice that the product is initialized to 1, not 0!

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;

while (( ans = 'Y') || (ans = 'y'))


{
//statements to read and process the number
cout << "Are there more numbers(Y/N)? ";
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

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

– Count controlled loops

– Ask before iterating

– Exit on flag condition

Slide 3- 192
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- 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

– Examples of exit on a flag condition for input


• List ended with a sentinel value
• Running out of input

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

while (grade < 90)


{
n++;
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

int n=1, number_of_student = 20;


grade = compute_grade(n);

while (( grade < 90) && ( n < number_of_students))


{
n++;
grade = compute_grade(n); // get grade
}

if (grade > 90){


cout << "Student number " << n << " has a
score of " << grade << endl;
}else{
cout << "No student has a high score.";
}
Slide 3- 197
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- 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.

• A block is a section of code enclosed by braces {}.

• Two types of scope rules:


• Local Scope
• Global Scope

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.

Global Scope Variables


• Variable declared outside of any block or function.
• Available throughout the entire program.
• Memory is allocated when the program starts and deallocated
when it terminates.

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;
}

Guess the output of the local variables x.


Slide 4- 202
Example of Global variables
#include <iostream>
Using namespace std;
Global variable g
int g = 100; available within the entire
program
int main(){
int x = 1;
cout << x << endl;
cout << g << endl;
{
cout << x << endl;
int x = 2;
cout << x << endl;
cout << g << endl;
}
cout << x << endl;
cout << g << endl;

return 0;
}

Guess the output of the local variables x. Slide 4- 203


Slide 3- 204
Slide 3- 205
Global Constant Variables
• A global variable whose value cannot be changed during the
execution of the program
• Declared using the ‘const’ keyword

• 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

Slides adapted from


Walter Savitch, “Problem
solving with C++”

Slide 2- 210

You might also like