Sei sulla pagina 1di 20

Memory Location in C+

+
Internal Memory

Example: PI (constant), radius


(variable)

Rules In Naming Identifiers


(variables)

Inside every computer is a component


called internal memory.

Computers internal memory is


composed of memory locations, each
with a unique numeric address.

Name must begin with a letter and


contain only letters, numbers, and
the underscore character

Memory location is similar to collection


of storage bins.

No punctuation marks, spaces, or


other special characters (such as $
or %) are allowed

Each address can store one item at a


time.

Cannot be a keyword (word that has


special meaning in C++)

Names are case sensitive

Memory Location

Example: discount is different


from DISCOUNT and from
Discount

Address or memory location can


contain numbers, text, or program
instructions

Valid or Invalid Variables

To use a memory location,


programmer must reserve the
address, called declaring.

totalSales

Total_Sal3s

Declaring a memory location is done


with an instruction that assigns a data
type, identifier and initial value
(optional).

Total Sales

total.Sales

4thQtrSales

Data Type - indicates what type of


information the address will store
(e.g., numeric or textual).

totalSale$

T0taLsales

Identifier - allows the programmer to


refer to the memory location
elsewhere in the program.

C++ Keywords

Keywords are predefined reserved


words or reserved identifiers that have
special meanings.

They cannot be used as identifiers in


your program

- Names made up by the programmer.


Types of Identifier

Variables - are memory locations


whose values can change during
runtime (when the program is
running). Most memory locations are
variables.
Constants - are memory locations
whose content cannot be changed
during program execution. Often
named in uppercase letters.

auto
const
double
float
int
short

struct
endl

string - is a user-defined data type,


can store zero (blank) or more
characters

Data Types

Memory locations come in different


types and sizes

A memory location will only accept an


item that matches its data type.

Data type of a memory location is


determined by the programmer when
declaring the location.

Fundamental Data Types in C++

short

int

float

double

bool

char

bool - stores Boolean values (true or 1


and false or 0)

short and int - store integers


(numbers without a decimal place)

When declaring a memory location a


data type and an identifier (variable or
constant) must be provided

Syntax for declaring a variable in C++


DataType Identifier ;

Examples:

float length;

Differences are range of values


and memory used (int has the
greater of both)

Int width;
string lastname;

Assigning Floating-point Values


to Integer Variables

Differences are range of values,


precision, and memory used
(double has the greater of
each)

Only one character stored at a


time

If a floating-point value is assigned to


an integer variable
o

The fractional part will be


truncated (i.e., chopped off
and discarded)

The value is not rounded


int rainfall = 3.88;
cout << rainfall;

char - stores characters (letter,


symbol, or number that will not be
used in a calculation)
o

string age;

float and double - store real numbers


(numbers with a decimal place)
o

string (user-defined data


type)

Declaring Memory Location

// Displays 3
String Literals

Can store a series of characters in


consecutive memory locations.

"Hello"

Sequence

Enclosed in a double quotation " "

Decision

Can define string data type in


programs string name;

Repetition

Case

1. Decision Structure
Char vs string literal constants

Makes a decision and then takes an


appropriate action based on that
decision

Example: waiting or crossing at


railroad tracks depending on signal
lights

Every decision boils down to on or off,


yes or no, 1 or 0.

Character literal constants initialize


char data types
o

Consist of one character in


single quotation marks

String literal constants initialize string


data types
o

Zero or more characters


enclosed in double quotation
marks

Using The IF Statement


The Single-Alternative if

Empty string ( ) is a valid


string literal constant.

One way to use an if is in a singlealternative selection wherein one


in which an action takes place only
when the result of the decision is true.

Reading in a String Statement

It takes the form:

if (Boolean expression)

- Reads in a string with no blanks

action/statement if true;

string name;
cin >> name;

When you write an if statement, you


use the keyword if, a Boolean
expression within parentheses, and
any statement that is the action that
occurs if Boolean expression is true.

Format of the if Statement

- Reads in a string that may contain blanks


string name;
getline(cin, name);
System (cls) ;

system( ) is used to run the DOS


commands from the C++

cls is the clear screen command

if (expression)
{
statement1;

Making Decisions /
Conditional Statements
Four Program Structures

statement2;

How the if Statement Works

If (expression) is true, then the


statement(s) in the body are
executed.

It takes the form:

if (Boolean expression)
action/statement if true;

If (expression) is false, then the


statement(s) are skipped.

else

Example if Statements

action/statement if false;

if (score >= 60)


cout << "You Passed!!" <<endl;

Format of the if-else Statement

if (number == 7)

cout<< "It is number 7!!" <<endl;

Allows a choice between statements


depending on whether (expression)
is true or false

if (expression)
if Statement Notes

Do not place ; after (expression)

The parentheses surrounding the


evaluated expression in the if
statement are essential

0 is false; any other value is true

Any value other than 0, even a


negative value, is considered to be
true.

{
statement set1;
}
else
{
statement set2;
}
How the if/else Works

Thus, the statement if (-5) cout<<


OK; would display OK.

Most frequently, you create an if


statements Boolean expression using
one of the six relational operators:

If (expression) is true, statement


set 1 is executed and statement set
2 is skipped.

If (expression) is false, statement


set 1 is skipped and statement set
2 is executed.

What if the two persons are the same


age?

The if/else Statement


The Dual-Alternative if

The dual alternative if, also called


if else structure, takes one action
when its Boolean expression is
evaluated as true, and uses an else
clause to define the actions to take
when the expression is evaluated as
false.

The program incorrectly says the


second person is older.

To solve this we must handle all three


possibilities.
if/else Statements

The if-else statement allows a choice


to be made between two possible
alternatives.

Sometimes a choice must be made


between more than two possibilities.

Consider using a the if/else if


statement.

Chain of if statements that test in


order until one is found to be true

if/else if also allows a choice of more


than two or many alternatives.

if/else if Format

if (expression)

When you make a character


comparison, you must remember that
C++ comparison are case sensitive.

The program genderCode for instance,


the character f is different from the
character F for Female.

Dont be surprised when the program


displays the message Invalid Code.

Assuming that Indentation has a


Logical Purpose, Adding an Unwanted
Semicolon and Forgetting Curly Braces

Remember that C++ ignore


indentation.

Only the placement of semicolons and


curly braces matters in determining
where statements and blocks end.

Ex: if (age1 > age2);

statement set 1;
else if (expression)
statement set 2;

else if (expression)
statement set n;

else;
Using a Trailing else

Using = Instead of ==

Used with if/else if statement when


none of (expression) is true

Dont use a single equal sign when


your intention is to compare values.

Provides a default statement or action

Can be used to catch invalid values or


handle other exceptional situations

Example: if (number = 7) //Notice the


single equal sign: if (number == 7)

if (genderCode == M')

Create a C++ program that determine if


you can vote else youre not yet eligible
to vote.

Making Unnecessary Comparisons

A program that determines whether


the user can vote.

Avoid Common Pitfalls


with if Statements

Forgetting that C++ comparisons are


case sensitive

cout << You can vote! ;

Assuming that indentation has a


logical purpose

cout << Youre not yet eligible to vote!;

Adding an unwanted semicolon

An if else statement that avoids the


unnecessary comparison

Forgetting curly braces

if (age >= 18)

Using = instead of ==

Making unnecessary comparisons

else

Forgetting that C++ comparisons


are case sensitive

cout << Youre not yet eligible to


vote!;

if (age >= 18)

if (age < 18)

cout << You can vote! ;

The switch Statement

Used to select among statements from


several alternatives

May sometimes be used instead of


if/else if statements

switch Statement Format

switch (expression)
{

Useful to execute a single case


statement without executing
statements following it

The switch statement can contain any


number of cases in any order. The
values in the case statements do not
have to occur in descending order nor
do they have to be consecutive.

The switch statement is not as


flexible as if; you use it only when you
have several outcomes that depends
on the value of a single variable or
expression.

case exp1: statement set 1;


break;
case exp2: statement set 2;
break;

case expn: statement set n;


default:

Using switch with a Menu

statement set ;

}
switch Statement Requirements
1) expression must be a char or an
integer variable or an expression that
evaluates to an integer value

switch statement is a natural choice


for menu-driven program

display menu

get user input

use user input as expression in


switch statement

use menu choices as exp to


test against in the case
statements

2) exp1 through expn must be constant


integer expressions and must be
unique in the switch statement
3) default is optional but recommended

Arrays

Is a special type of variable


which can contain or hold one
or more values of the same data
type with reference to only one
variable name.

It can be distinguished through


a pair of square brackets [ ]

How the switch Statement Works

1) expression is evaluated
2) The value of expression is compared
against exp1 through expn.
3) If expression matches value expi,
the program branches to the
statement(s) following expi and
continues to the end of the switch
4) If no matching value is found, the
program branches to the statement
after default:
The break Statement

Used to stop execution in the current


block

Also used to exit a switch statement

Index (or element)

The number in square brackets

The index always start with 0

The array whose index is zero is


the first element in the array

for Loop

The for loop is ideally used to


manipulate an array.

Array Initialization
General Syntax:
datatype arrayname [index] ;

Example:

int score [10] ;

float lenght [8] ;

In C++, an array consisting of 5


variables of type int can be declared
as follows:

Array Initialization Output

One Dimensional
Array Initialization

One Dimensional
Array Initialization

Sample Program
(without array)

int score [5] ;


int
data type of array
variable (base type)
score variable used for the
array
[5]
size)

size of the array (declared

Is also written as:

int score[0], score[1], score[2], score[3],


score[4];

This array can be viewed in the


computer as:

One Dimensional Array Initialization

int score[3];
score[0] = 90;
score[1] = 95;

What is Two-Dimensional Array?

score[2] = 100;

Arrays are also useful in forming


tables or matrices.

It can define one array for multiple


sets of data.

Indexed variables not provided with


initializers are initialized to zero.

It is like a table in a spreadsheet (has


rows and columns)

One-Array Initialization
Source Code

Use two size (index) declarators in


definition

int score[3] = {90, 95, 100};

int score[ ] = {90, 95, 100};

int number[4][3];

[4]=Number of rows

Sets the field width to be used on


output operation

Example: cout<< setw(20)

[3]=Number of columns
#include <iomanip>

A header file for input/output


manipulator

Is a library that is used to manipulate


the output of our program
Some Manipulators
Used in the Program

LEVELS OF
DATA ORGANIZATION
What is Data?

These are raw facts that are used as


basis for manipulation and
computation which are considered to
be the input.

Unorganized facts that need to be


processed.

Raw data is basically has no meaning.

setiosflags includes:

ios::fixed

ios::showpoint

setprecision

setw

DATA vs INFORMATION

ios::fixed

Display floating point values using


normal notation (will not use a
scientific notation)
Therefore well never see a number
displayed as 1.06e+12 or something
similar.

These are processed data that are


considered to be the results or the
output.
When data is processed, organized,
structured or presented in a given
context so as to make it useful, it is
called Information.
Levels of
Data Organization

ios::showpoint

Display a decimal and extra zeros,


even when not needed.

Some Manipulators
Used in the Program

The proper way to invoke these two


statements are as follows:

Bit
Byte
Field
Record
File
Database

Bit

cout.setf(ios::fixed);

It is the smallest form of data.

cout.setf(ios::showpoint);

It consists of binary digits (0 and 1)

setprecision

It is a statement that specifies how


many decimal points to print out.

Example if we have the number


54.271123 and used
cout.precision(2)- it would print out:
54.27 to the console.

setw

Byte (8 bits)
It is the smallest unit of data.
It is equal to one character (Ex. A-Z 09 and any symbol).
A character is the most basic element
of data that can be observed and
manipulated.

Field - it is a group of characters


taken as one. It is a logical unit of
data.
RECORD

Ex. Name, Address, Phone

Operators and
Mathematical
Expressions

Record - it is a group of related fields


pertaining to one entity.

One record is displayed from


the Employee Table above. The
table contains 8 fields.

Mathematical Expressions

An expression can be a constant, a


variable, or a combination of constants
and variables combined with
operators.

Ex. Student, Professor, Course,


Schedule

Can create complex expressions using


multiple mathematical operators.

Database

Example mathematical expressions

File - it is a group of related records


pertaining to subject. A file is
sometimes called a table.

It is a collection of related files


pertaining to one subject.

2
height

Examples of Business Databases

Telephone book

Student data

Music

Fingerprint database

Dictionaries

Customer data

Real estate listings

Hospital/patient data

Inventory
Levels of Data Organization

a+b/c
Using Mathematical Expressions

Can be used in assignment


statements, with cout, and in other
types of statements

Examples:
area = 2 * PI * radius;
cout << "border is: " <<
(2*(l+w));

Assignment Statement

Uses the equal sign = operator

Has a single variable on the left side


and a value on the right side

Copies the value on the right into the


variable on the left
x = 5;

y = 6;

z = 4;

x = x + y;
y = y + 4;

Example: Evaluate the following


expressions
a = (5 + 4) * 3

z = 5 + x + z;

b=5+4*3

Operators

These are the symbols that tells the


compiler to perform a specific
mathematical or logical manipulation.

c = 50 / 10 * 2
d = 60 - 20 + 4 / 2 * 10
Division (/) Operator

Types of Operators:

1. Arithmetic
2. Relational

C++ division operator (/) performs


integer division if both operands are
integers
cout << 13 / 5;

3. Logical

cout << 2 / 4;

Arithmetic Operators

// displays 2
// displays 0

If either operand is floating-point, the


result is floating-point
cout << 13 / 5.0; // displays 2.6
cout << 2.0 / 4;

// displays 0.5

Modulus (%) Operator

Precedence of Operators

C++ modulus operator (%) computes


the remainder resulting from integer
division
cout << 9 % 2;

// displays 1

% requires integers for both operands


cout << 9 % 2.0; // error

Algebraic Expressions

Associativity of Operators

- (unary negation) associates right to


left

* / % + - all associate left to right

parentheses ( ) can be used to


override the order of operations
2+2 * 22 =4

Multiplication requires an operator


Area = lw is written as Area = l *

w;

There is no exponentiation operator

Area = s2 is written as Area =


pow(s,2);

Parentheses may be needed to


maintain order of operations

(2 + 2) * 2 2 = 6
2 + 2 * (2 2) = 2
(2 + 2) * (2 2) = 0

is written as m = (y2-y1)/
(x2-x1);

x == 10
x != 8
x == 8

Assigns 0 for false, 1 for true

Do not confuse = and ==

Logical Operators

Some Predefined Functions in C++

Predefined functions - are functions


that are built into C++ to perform
some standard operations.

These functions were predefined for


you, meaning that you didn't have to
tell the computer how to compute the
square root and power of a number.

The header file required for


mathematical functions is #include
<cmath>

Used to create relational expressions


from other relational expressions.
Sometimes referred to as Boolean
operators.

Truth Table for the && (logical


AND) operator

Relational Operators

Used to compare numbers to


determine relative order
Relational Operators:

Truth Table for the || (logical OR)


Operator

Relational Expressions

Relational expressions are Boolean


(i.e., evaluate to true or false)
Examples:
12 > 5 is true
7 <= 5 is false
if x is 10, then

Logical Operator Examples


int x = 12, y = 5, z = -4;

Advantages of a RDBMS
Logical Precedence
Highest !
&&
Lowest

||

Example:

All data is stored in the database


Data redundancy is reduced
Easier to maintain data integrity
Eliminates the dependence between
programs and data.
The database can operate as a
standalone application.

(2 < 3) || (5 > 6) && (7 > 8)

Properties of a Relation/Table

is true because AND is done before OR

1. A relation consists of a set of attributes


with unique names (i.e., attribute names
cannot repeat in the SAME table). It doesnt
matter in which order the attributes are
listed.

More on Precedence

2. The values of attributes fall into a known


domain or legal values. For example, the
number of students in a class cannot be -20
or 3.26; it has to be a positive integer.

Example:
8 < 2 + 7 || 5 == 6

is true

RDBMS and TABLE


RELATIONSHIPS IN ACCESS

3. Each tuple (row) in the database is


unique. That is, records do not repeat.

Relational Database

The Relational Model was developed in


1970 by E.F. Codd
A relation is nothing but a
table/entities that consists of
records/tuples (rows) and
fields/attributes (columns).
A Relational Database Management
System (RDBMS) is a piece of
software that manages groups of
tables which are related to one
another.
MS Access is an example of RDBMS.

Relational Database Terminology

To avoid records from repeating, we


have what is called "Primary Key ".
Primary key can uniquely determine a
record.
The primary key cannot take NULL
value (means a record cannot exist
without a unique identifier). For
example, Student_ID is the primary
key for STUDENT table. One cannot
enter a students information without
his/her Student_ID into the STUDENT
table.

Types of Relational Keys


a)
b)
c)
d)

Candidate Key
Alternate Key
Primary Key
Foreign Key

Candidate Keys
- A minimal set of attributes in a table that
uniquely identifies a record. When there is
more than one attribute in the candidate key,
it is called composite key.
Alternate Keys
- Any candidate key that is not selected to
be a primary key can be an alternate key.

Primary Key
- A candidate key that is chosen to
represent a record uniquely. That is, a table
may consist of many candidate keys, but
ONLY ONE can be selected as a primary key.
Note that a primary key can have more than
one attribute.

Sample use: some information about a


record must be confidential; the
confidential information is put in a
table with a one-to-one relationship to
the main table, and access to the
second table is restricted.

One-to-one

Foreign Keys
- is a column or group of columns in a
relational database table that provides a link
between data in two tables.
Table Relationship
A Relationship - is how you tell the
program that a piece of information means
the same thing in more than one table.
Table relationships can be created between
two tables as long as they have a common
attribute.
Relationships are created using a Primary
Key from one table and linking it to a related
field in another table (now called a Foreign
Key).

2. One-to-many

Primary keys are used to uniquely


identify a table while a foreign key is
used to link tables using one of the
primary keys.

Very common, one record in the


primary table can be linked to many
records in the related table, but each
record in the related table can be
linked to only one in the primary table.
Examples: A mother can have many
children, but each child has only one
mother; a salesman can make many
sales, but any given sale is credited to
only one salesman; a person can have
many library books checked out but
each book can be checked out by only
one person (at a time).

One-to-many

Types of Relationships between Tables


1. One-to-one

Rarely used, a record in the primary


table corresponds to one and only one
record in the related table. (Rare
because fields that would go into the
second table are usually just put into
the primary table itself.)

3. Many-to-many

Very common, when a single record in


one table can relate to many records
in another, and a single record in that
second table can also relate to many
records in the first.
Examples: one author can write many
books, and one book can have several
authors; one student can take many

classes and one class will have many


students; one order can contain many
items, and one item can appear in
many orders.
These relationships are not
established directly; they must be
accomplished through a junction
table like Grades below.

orders assigned to that employee in


the Orders table.
You cannot change a primary key
value in the primary table if doing so
would create orphan records. For
example, you cannot change an order
number in the Orders table if there are
line items assigned to that Order in
the Order Details table.
Referential Integrity Options

Cascade Update Related Fields

Enforce Referential Integrity

An orphan record is one that refers


to a nonexistent record in another
table, such as the orders placed by
nonexistent customers.
The purpose of using referential
integrity is to prevent orphan records
and to keep references synchronized
so that you don't have any records
that reference other records that no
longer exist.
You enforce referential integrity by
enabling it for a table relationship.
Once enforced, Access rejects any
operation that would violate
referential integrity for that table
relationship.
Access rejects updates that change
the target of a reference, and also
deletions that remove the target of a
reference.

- permits the change of the primary key of


the one table and modifies the related
records in the many table to match (e.g. if
a library patron loses her card, any books
she has checked out can be switched to her
new card number.)
Referential Integrity
Cascade Delete Related Fields
- permits the deletion of a record in the
one table and deletes all related records in
the many table.
** These options are usually turned on when
needed and turned OFF the rest of the time.
Edit a Relationship

Delete a Relationship

After you have enforced referential


integrity, the following rules apply:

You cannot enter a value in the foreign


key field of a related table if that value
doesn't exist in the primary key field of
the primary table doing so creates
orphan records.
You cannot delete a record from a
primary table if matching records exist
in a related table. For example, you
cannot delete an employee record
from the Employees table if there are

In the Relationships window, double


click the relationship line to reopen the
Edit Relationships box.

In the Relationships window, right click


the relationship line and choose Delete
from the pop-up menu, or click Delete
in the keyboard.

Repetition Structure
Repeating Program Instructions

The repetition structure, or loop,


processes one or more instructions
repeatedly.

Loop allows you to perform statements


repeatedly, and just as importantly, so
to stop the action when warranted.

Frequently, its the decision-making


that makes the programs seems
smart, but looping makes program
powerful.

By using loops, you can write one


set of instructions that executes
thousands or even millions of
times.

Every loop contains a Boolean


condition that controls whether the
instructions are repeated.

A looping condition says whether to


continue looping (repeating) through
instructions

A loop exit condition says whether


to stop looping (repeating) through the
instructions

Instructions in a pretest loop may not


be processed if the condition initially
evaluates to false

The repeatable instructions in a loop


are called the loop body

The condition in a loop must evaluate


to a Boolean value

Performing Loops

Notice the use of the diamond symbol.


A loop tests a condition, and if the
condition exists (True), it performs an
action. Then it tests the condition
again. If the condition still exists, the
action is repeated. This continues until
the condition no longer exists.

In the flowchart, the question is x <


y? is asked. If the answer is yes, then
Process A is performed. The question
is x < y? is asked again. Process A is
repeated as long as x is less than y.
When x is no longer less than y, the
repetition stops and the structure is
exited.

Make hay while the sunshine.


-

The while the sunshine is the


looping condition, because it tells you
when to continue making hay.

Make hay until the sun is no longer


shining.
- In this case until the sun is no longer
shining is the loop exit condition, because it
indicates when you should stop making hay.

Therefore every looping condition has


an opposing loop exit condition.

C++ uses looping conditions in


repetition structures

A repetition structure can be pretest or


posttest

In a pretest loop, the condition is


evaluated before the instructions in
the loop are processed

In a posttest loop, the condition is


evaluated after the instructions in the
loop are processed
In both cases, the condition is
evaluated with each repetition
The instructions in a posttest loop will
always be processed at least once

x < y?

YES
YES Process A

The Increment and Decrement


Operators

++ adds one to a variable


x++; is the same as x = x + 1;

-- subtracts one from a variable

x--; is the same as x = x 1;

can be used in prefix mode (before) or


postfix mode (after) a variable
3 Basic Types of Loop
a) while
b) for

c) do while

a) The while Loop


In C++, you can use a while loop to
repeat actions.
Format of while loop
Initialization ;
while (expression)
{ statement(s); action while
expression is true
Update the initial value ;
}
How the while Loop Works

In while loop, a Boolean expression is


evaluated. If the expression in the
while statement is true, the resulting
action, called the loop body (which
can be a single statement or a block of
statements) executes, and the
Boolean expression is tested again.
If it is false, the loop is over and the
program execution continues with the
statement that follows the while
statement.
The cycle of execute-test-execute-test
continues as long as the Boolean
expression continues to be evaluated
as true.
Therefore, a while loop is a repetition
structure that executes as long as a
tested expression is true.
While, a loop body contains the
statements that execute within a
loop.

Initialization;
while (expression)
{

statement(s);
Update;

expression is evaluated

if it is true, the statement(s)


are executed, and then
expression is evaluated again

if it is false, the loop is exited

while Loop Example

int x = 5; // initialization of variable


//(x is the loop control variable)
while (x >= 0)
{

// boolean condition

cout << x << " "; // loop body


x--;

// update

// end while

Produces Output:
5 4 3 2 1 0
Loop Control Variable

A loop control variable is a


variable that controls the execution of
a loop body.

Loop control variable contain three


pieces of information:

The loop control variable is initialized.

The loop control variable is compared


to another value.

Within the loop body, the loop control


variable is altered.

Exiting the Loop

The loop must contain code to allow


expression to eventually become
false so the loop can be exited

Otherwise, you have an infinite loop or


endless loop (i.e., a loop that does not
stop)

Example of infinite loop:

x = 5;
while (x > 0)
cout << x;

// infinite loop because


// x is always > 0

Sentinel

Some loops require the user to enter a


special sentinel value to end the loop .

Sentinel is a value that determines


when a loop will end.

It is a special value that cannot be


confused with a valid value, e.g. enter
-1 to stop

Used to terminate input when user


may not know how many values will
be entered

Sentinel Example

Avoiding Common Pitfalls with Loops

int points;

cout << "Enter points earned "


<< "(or -1 to quit): ";

cin >> points;


while (points != -1) // -1 is the sentinel

cout << "Enter points earned: ";


cin >> points;
}

Sentinel

Some loops require the user to enter a


special sentinel value to end the loop.
Sentinel is a value that determines
when a loop will end.
It is a special value that cannot be
confused with a valid value, e.g. enter
-1 to stop
Used to terminate input when user
may not know how many values will
be entered

int points;

Sentinel
Example
cout << "Enter
points earned "
<< "(or -1 to quit): ";
cin

>> points;

while (points != -1) // -1 is the

Adding an unwanted semicolon


Forgetting curly braces
Failing to initialize a loop control
variable (initialization value)
Failing to alter a loop control
variable
Avoiding Common Pitfalls with
Loops
Making the same types of
mistakes, you can make with
selections (conditional), including
forgetting that C++ is case
sensitive, assuming indentation
has logical purpose, using =
instead of ==

Adding an unwanted semicolon


int number = 1;
while (number <= 10) ;

No
semicolon

{
cout << number << endl;
number ++;
}

Forgetting curly braces and Failing to


alter a loop control variable

To calculate a total or average, you


use a counter, accumulator or both.

int number = 1;

A counter - is a numeric variable used


for counting something. It is a variable
that is incremented or decremented
each time a loop repeats

An accumulator - is a numeric
variable used for accumulating
(adding together) multiple values

Two tasks are associated with counters


and accumulators: initializing and
updating.

Initializing means assigning a


beginning value to a counter or
accumulator (usually 0) happens
once, before the loop is processed.

Updating (or incrementing) means


adding a number to the value of a
counter or accumulator.

A counter is updated by a constant


value (usually 1)

An accumulator is updated by a value


that varies

Update statements are placed in the


body of a loop since they must be
performed at each iteration

while (number <= 10)


cout << number << endl;
number ++;
The while loop ends at the
semicolon. The statements
that increments number is
not part of the loop.

Failing to initialize a loop control


variable
int number;

Contains a loop with


an uninitialized loop

while (number <= 10) ;


{
cout << number << endl;
number ++;
}
In C++ an uninitialized variable has an
unknown value; programmers call this
unknown value a garbage value.
Counters and Accumulating Totals
Using Counters and Accumulators

Many computer programs display


totals.

The += operator is used to


accumulating total.

For instance, when you receive a


credit card or telephone service bill,
you are usually provided with
individual transaction details, but it is
the total bill in which you are most
interested.

Example:

Similarly, some programs total the


number of credit hours generated by
college students, the gross payroll for
all employees and the like.
These totals are accumulated that
is, gathered together and added into a
final sum, by processing individual
records one at a time in a loop.

total += num is the same as


total = total + num;

Repetition Structure
(continued)
Counter-Controlled Loops

Loops can be controlled using a


counter rather than a sentinel value

These are called counter-controlled


loops

Miguel Music Companys Program

The sales manager at Miguels Music


Company wants a program that allows him to
enter the quarterly sales amount made in
each three regions: Region 1, Region 2, and
Region 3. The program should calculate the
total quarterly sales and then display the
result on the screen.

If the expression is false the loop will


be exited, bypassing the body of the
for loop.

Update represents any C++


statements that take place after
executing the loop body.

Miguel Music Companys Program

The program will use a counter to


ensure that the sales manager enters
exactly three sales amounts.

Usually contains an expression that


updates the counter variable

It will use an accumulator to total the


sales amount.

In for loop, the variable is often


declared and initialized inside the for
loop statement.
for (int x=1; x <= 10 ; x++)
cout<<x << " " ;

The for Loop

for Loop - can be used as an


alternative to the while loop.

Solution to for
Square Loop

It is frequently used in a definite loop


or a loop that must execute a definite
number of times.

\t is used for tab (must be place in


cout statement)

cout<< \t

It can be used to replace any while


loop.

Useful for counter-controlled loop

Format:
for( initialization; expression ; update )
{

Review of
Pretest vs. Posttest Loops

Whether you use a while loop or for


loop, the loop body might never
execute.

Both of these loops are pretest loops


loops in which the loop control
variable is tested before the loop body
is executed.

Sometimes, you want to ensure that a


loop body executes at least once.

That way, the code definitely would


execute one time even if the loop was
never entered.

An alternative is to use posttest loop


one in which the loop control variable
is test after the loop body executes.

Therefore, the instructions in a


posttest loop will always be processed
at least once

While the instructions in a pretest loop


may not be processed if the condition
initially evaluates to false

1 or more statements;
}

Initialization represent any steps you


want to take at the beginning of the
statement.
Most often this includes initializing a
loop control variable.

Expression (condition) any C++


expression that is evaluated as false
or true.

If the expression is true any


statements in the body of the for loop
are executed.

The do-while Loop

do-while Loop controls a loop that


tests the loop-continuing condition at
the end, or bottom, of the loop.

do-while: a posttest loop (expression is


evaluated after the loop executes)

Format:

b) In a for loop, the loop body might


never execute.
c) The do-while loop controls a loop
that tests the loop-continuing
condition at the top of the loop.

c) The do-while loop controls a loop


that tests the loop-continuing
condition at the bottom of the loop.

do
{
1 or more statements;
} while (expression);

Answer

Nested Loop

A nested loop is a loop inside the body


of another loop

You can place any statements you


need within a loop body.

Deciding Which Loop to Use

while: pretest loop (loop body may


not be executed at all)

You can nest any type of loop (while,


for, do-while).

do-while: posttest loop (loop body will


always be executed at least once)

A loop that completely contains


another is an outer loop (row).

for: pretest loop (loop body may not


be executed at all); has initialization
and update code; is useful with
counters or if precise number of
repetitions is known

A loop that falls entirely within the


body of another is an inner loop
(column).

You can place one loop (the inner, or


nested loop) inside another loop (the
outer loop)

1) Which of the following is false?


a) The while loop is a pretest loop.

Potrebbero piacerti anche