0% found this document useful (0 votes)
12 views94 pages

Chapter 05

Chapter 5 covers loops and file handling in programming, detailing increment and decrement operators, while loops, do-while loops, for loops, and their applications in input validation and counters. It explains how to manage loop execution and avoid infinite loops, as well as introduces file processing for data storage, including reading from and writing to files. The chapter emphasizes the importance of using the appropriate loop structure based on the specific programming scenario.

Uploaded by

azimah6642
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views94 pages

Chapter 05

Chapter 5 covers loops and file handling in programming, detailing increment and decrement operators, while loops, do-while loops, for loops, and their applications in input validation and counters. It explains how to manage loop execution and avoid infinite loops, as well as introduces file processing for data storage, including reading from and writing to files. The chapter emphasizes the importance of using the appropriate loop structure based on the specific programming scenario.

Uploaded by

azimah6642
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

Chapter 5:

Loops and Files

© Pearson Education Limited 2015


The Increment and Decrement
Operators
++ is the increment operator.

It adds one to a variable.

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

++ can be used before (prefix) or after (postfix) a


variable:
++val; val++;

© Pearson Education Limited 2015


The Increment and Decrement
Operators
-- is the decrement operator.

It subtracts one from a variable.

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

-- can be also used before (prefix) or after


(postfix) a variable:
--val; val--;

© Pearson Education Limited 2015


Increment and Decrement
Operators in Program 5-1

Continued…

© Pearson Education Limited 2015


Increment and Decrement
Operators in Program 5-1

© Pearson Education Limited 2015


Prefix vs. Postfix
++ and -- operators can be used in
complex statements and expressions
In prefix mode (++val, --val) the
operator increments or decrements, then
returns the value of the variable
In postfix mode (val++, val--) the
operator returns the value of the variable,
then increments or decrements

© Pearson Education Limited 2015


Prefix vs. Postfix - Examples
int num, val = 12;
cout << val++; // displays 12,
// val is now 13;
cout << ++val; // sets val to 14,
// then displays it
num = --val; // sets val to 13,
// stores 13 in num
num = val--; // stores 13 in num,
// sets val to 12

© Pearson Education Limited 2015


Notes on Increment and
Decrement
Can be used in expressions:
result = num1++ + --num2;
Must be applied to something that has a location
in memory. Cannot have:
result = (num1 + num2)++;
Can be used in relational expressions:
if (++num > limit)
pre- and post-operations will cause different
comparisons

© Pearson Education Limited 2015


5.2
Introduction to Loops: The while
Loop

© Pearson Education Limited 2015


Introduction to Loops:
The while Loop
Loop: a control structure that causes a
statement or statements to repeat
General format of the while loop:
while (expression)
statement;
statement; can also be a block of
statements enclosed in { }

© Pearson Education Limited 2015


The while Loop – How It Works
while (expression)
statement;
expression is evaluated
if true, then statement is executed, and
expression is evaluated again
if false, then the loop is finished and
program statements following statement
execute

© Pearson Education Limited 2015


The Logic of a while Loop

© Pearson Education Limited 2015


The while loop in Program 5-3

© Pearson Education Limited 2015


How the while Loop in Program 5-
3 Lines 9 through 13 Works

© Pearson Education Limited 2015


Flowchart of the while Loop in
Program 5-3

© Pearson Education Limited 2015


The while Loop is a Pretest Loop
expression is evaluated before the
loop executes. The following loop will
never execute:

int number = 6;
while (number <= 5)
{
cout << "Hello\n";
number++;
}

© Pearson Education Limited 2015


Watch Out for Infinite Loops
The loop must contain code to make
expression become false
Otherwise, the loop will have no way of
stopping
Such a loop is called an infinite loop,
because it will repeat an infinite number of
times

© Pearson Education Limited 2015


Example of an Infinite Loop

int number = 1;
while (number <= 5)
{
cout << "Hello\n";
}

© Pearson Education Limited 2015


5.3
Using the while Loop for Input
Validation

© Pearson Education Limited 2015


Using the while Loop for
Input Validation
Input validation is the process of
inspecting data that is given to the
program as input and determining whether
it is valid.

The while loop can be used to create input


routines that reject invalid data, and repeat
until valid data is entered.

© Pearson Education Limited 2015


Using the while Loop for
Input Validation
Here's the general approach, in
pseudocode:

Read an item of input.


While the input is invalid
Display an error message.
Read the input again.
End While

© Pearson Education Limited 2015


Input Validation Example

cout << "Enter a number less than 10: ";


cin >> number;
while (number >= 10)
{
cout << "Invalid Entry!"
<< "Enter a number less than 10: ";
cin >> number;
}

© Pearson Education Limited 2015


Flowchart for Input Validation

© Pearson Education Limited 2015


Input Validation in Program 5-5

© Pearson Education Limited 2015


5.4
Counters

© Pearson Education Limited 2015


Counters
Counter: a variable that is incremented or
decremented each time a loop repeats
Can be used to control execution of the
loop (also known as the loop control
variable)
Must be initialized before entering loop

© Pearson Education Limited 2015


A Counter Variable Controls the
Loop in Program 5-6

Continued…

© Pearson Education Limited 2015


A Counter Variable Controls the
Loop in Program 5-6

© Pearson Education Limited 2015


5.5
The do-while Loop

© Pearson Education Limited 2015


The do-while Loop
do-while: a posttest loop – execute the loop,
then test the expression
General Format:
do
statement; // or block in { }
while (expression);

Note that a semicolon is required after


(expression)

© Pearson Education Limited 2015


The Logic of a do-while Loop

© Pearson Education Limited 2015


An Example do-while Loop

int x = 1;
do
{
cout << x << endl;
} while(x < 0);

Although the test expression is false, this loop will


execute one time because do-while is a posttest
loop.

© Pearson Education Limited 2015


A do-while Loop in Program 5-7

Continued…

© Pearson Education Limited 2015


A do-while Loop in Program 5-7

© Pearson Education Limited 2015


do-while Loop Notes
Loop always executes at least once
Execution continues as long as
expression is true, stops repetition
when expression becomes false
Useful in menu-driven programs to bring
user back to menu to make another choice
(see Program 5-8 on pages 276-277)

© Pearson Education Limited 2015


5.6
The for Loop

© Pearson Education Limited 2015


The for Loop
Useful for counter-controlled loop

General Format:

for(initialization; test; update)


statement; // or block in { }

No semicolon after the update expression or


after the )

© Pearson Education Limited 2015


for Loop - Mechanics
for(initialization; test; update)
statement; // or block in { }

1) Perform initialization
2) Evaluate test expression
If true, execute statement
If false, terminate loop execution
3) Execute update, then re-evaluate test
expression

© Pearson Education Limited 2015


for Loop - Example

int count;

for (count = 1; count <= 5; count++)


cout << "Hello" << endl;

© Pearson Education Limited 2015


A Closer Look
at the Previous Example

© Pearson Education Limited 2015


Flowchart for the Previous Example

© Pearson Education Limited 2015


A for Loop in Program 5-9

Continued…

© Pearson Education Limited 2015


A for Loop in Program 5-9

© Pearson Education Limited 2015


A Closer Look at Lines 15 through
16 in Program 5-9

© Pearson Education Limited 2015


Flowchart for Lines 15 through 16
in Program 5-9

© Pearson Education Limited 2015


When to Use the for Loop
In any situation that clearly requires
an initialization
a false condition to stop the loop
an update to occur at the end of each iteration

© Pearson Education Limited 2015


The for Loop is a Pretest Loop
The for loop tests its test expression
before each iteration, so it is a pretest
loop.
The following loop will never iterate:

for (count = 11; count <= 10; count++)


cout << "Hello" << endl;

© Pearson Education Limited 2015


for Loop - Modifications
You can have multiple statements in the
initialization expression. Separate
the statements with a comma:
Initialization Expression
int x, y;
for (x=1, y=1; x <= 5; x++)
{
cout << x << " plus " << y
<< " equals " << (x+y)
<< endl;
}

© Pearson Education Limited 2015


for Loop - Modifications
You can also have multiple statements in
the test expression. Separate the
statements with a comma:
Test Expression

int x, y;
for (x=1, y=1; x <= 5; x++, y++)
{
cout << x << " plus " << y
<< " equals " << (x+y)
<< endl;
}

© Pearson Education Limited 2015


for Loop - Modifications
You can omit the initialization
expression if it has already been done:

int sum = 0, num = 1;


for (; num <= 10; num++)
sum += num;

© Pearson Education Limited 2015


for Loop - Modifications
You can declare variables in the
initialization expression:

int sum = 0;
for (int num = 0; num <= 10;
num++)
sum += num;

The scope of the variable num is the for loop.

© Pearson Education Limited 2015


5.7
Keeping a Running Total

© Pearson Education Limited 2015


Keeping a Running Total
running total: accumulated sum of numbers from
each repetition of loop
accumulator: variable that holds running total
int sum=0, num=1; // sum is the
while (num <= 10) // accumulator
{ sum += num;
num++;
}
cout << "Sum of numbers 1 – 10 is"
<< sum << endl;

© Pearson Education Limited 2015


Logic for Keeping a Running Total

© Pearson Education Limited 2015


A Running Total in Program 5-12

Continued…

© Pearson Education Limited 2015


A Running Total in Program 5-12

© Pearson Education Limited 2015


5.8
Sentinels

© Pearson Education Limited 2015


Sentinels
sentinel: value in a list of values that
indicates end of data

Special value that cannot be confused with


a valid value, e.g., -999 for a test score

Used to terminate input when user may


not know how many values will be entered

© Pearson Education Limited 2015


A Sentinel in Program 5-13

Continued…

© Pearson Education Limited 2015


A Sentinel in Program 5-13

© Pearson Education Limited 2015


5.9
Deciding Which Loop to Use

© Pearson Education Limited 2015


Deciding Which Loop to Use
The while loop is a conditional pretest loop
Iterates as long as a certain condition exits
Validating input
Reading lists of data terminated by a sentinel

The do-while loop is a conditional posttest loop


Always iterates at least once
Repeating a menu

The for loop is a pretest loop


Built-in expressions for initializing, testing, and updating
Situations where the exact number of iterations is known

© Pearson Education Limited 2015


5.10
Nested Loops

© Pearson Education Limited 2015


Nested Loops
A nested loop is a loop inside the body of
another loop
Inner (inside), outer (outside) loops:

for (row=1; row<=3; row++) //outer


for (col=1; col<=3; col++)//inner
cout << row * col << endl;

© Pearson Education Limited 2015


Nested for Loop in Program 5-14

Inner Loop

Outer Loop

© Pearson Education Limited 2015


Nested Loops - Notes
Inner loop goes through all repetitions for
each repetition of outer loop

Inner loop repetitions complete sooner


than outer loop

Total number of repetitions for inner loop


is product of number of repetitions of the
two loops.

© Pearson Education Limited 2015


Coding Challenge – Distance
Travelled
Write a program that:
asks the user for the average speed of a
vehicle in kilometres per hour.
validate that the speed is not negative
asks how many hours it has travelled.
validate that the travelled hours is not less
than 1 hour
use loop to calculate the travelled distance of
the vehicle

© Pearson Education Limited 2015


and display the distance that vechile has
traveled for each hour
ex.
Hour Distance Traveled
----------------------------------
1 150
2 300
3 450

© Pearson Education Limited 2015


5.11
Using Files for Data Storage

© Pearson Education Limited 2015


Why need file processing?
When a program needs to save data for
later use, it writes the date in a file
Then the data can be read from the file at
a later time
Files are used for permanent storage
instead of keyboard, monitor screen for
program input, output (temporary)
Allows data to be retained between
program runs
© Pearson Education Limited 2015
Programs that are used in daily
business operations
Rely extensively on files
Payroll programs
employee data are kept in file
Inventory programs
Company’s products are kept in file
Accounting system
Company’s financial operations are kept in files

© Pearson Education Limited 2015


Terminology
Saving data in a file :
Also means writing data to a file
Is called output file, since program stores its
output in the file
Retrieving data from a file:
Also means reading data from a file
When a piece of data is read from file, it is
copied from the file into a variable in RAM
Is called input file, since program gets input
from the file
© Pearson Education Limited 2015
File stream object
Is created in memory
Is associated with a specific file
Provides a way for the program to work
with the file
Why called stream object?
A file is a stream of data

© Pearson Education Limited 2015


Using Files for Data Storage
Steps:
Include fstream header file
Open the file
Use the file (read from, write to, or both)
Close the file

© Pearson Education Limited 2015


Files: What is Needed
Use fstream header file for file access
File stream types:
ifstream for input from a file
ofstream for output to a file
fstream for input from or output to a file
Define file stream objects:
ifstream infile;
ofstream outfile;

© Pearson Education Limited 2015


Opening Files
Create a link between file name (outside the program)
and file stream object (inside the program)
Use the open member function:
infile.open("inventory.dat");
outfile.open("report.txt");
Filename may include drive, path info.
Output file will be created if necessary; existing file will
be erased first
Input file must exist for open to work

© Pearson Education Limited 2015


Testing for File Open Errors
Can test a file stream object to detect if an open
operation failed:
infile.open("test.txt");
if (!infile)
{
cout << "File open failure!";
}
Can also use the fail member function

© Pearson Education Limited 2015


Using Files
Can use output file object and << to send
data to a file:
outfile << "Inventory report";
Can use input file object and >> to copy
data from file to variables:
infile >> partNum;
infile >> qtyInStock >>
qtyOnOrder;

© Pearson Education Limited 2015


Writing to file (Example 5-15)
// This program writes data to a file.
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ofstream outputFile;
outputFile.open("demofile.txt");

© Pearson Education Limited 2015


Example 5-15
cout << "Now writing data to the file.\n";

// Write four names to the file.


outputFile << "Bach\n";
outputFile << "Beethoven\n";
outputFile << "Mozart\n";
outputFile << "Schubert\n";

// Close the file


outputFile.close();
cout << "Done.\n";
return 0;
}
© Pearson Education Limited 2015
Example 5-18
// This program writes user input to a file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
ofstream outputFile;
string name1, name2, name3;

// Open an output file.


outputFile.open("Friends.txt");

© Pearson Education Limited 2015


// Get the names of three friends.
cout << "Enter the names of three friends.\n";
cout << "Friend #1: ";
cin >> name1;
cout << "Friend #2: ";
cin >> name2;
cout << "Friend #3: ";
cin >> name3;
// Write the names to the file.
outputFile << name1 << endl;
outputFile << name2 << endl;
outputFile << name3 << endl;
cout << "The names were saved to a file.\n";

// Close the file


outputFile.close();
return 0;
}
© Pearson Education Limited 2015
Reading from file (Example 5-19)
// This program reads data from a file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
ifstream inputFile;
string name;

inputFile.open("Friends.txt");
cout << "Reading data from the file.\n";

© Pearson Education Limited 2015


Reading from file (Example 5-19)
inputFile >> name; // Read name 1 from the file
cout << name << endl; // Display name 1

inputFile >> name; // Read name 2 from the file


cout << name << endl; // Display name 2

inputFile >> name; // Read name 3 from the file


cout << name << endl; // Display name 3

inputFile.close(); // Close the file


return 0;
}

© Pearson Education Limited 2015


Using Loops to Process Files
The stream extraction operator >> returns
true when a value was successfully read,
false otherwise

Can be tested in a while loop to continue


execution as long as values are read from
the file:
while (inputFile >> number) ...

© Pearson Education Limited 2015


Closing Files
Use the close member function:
infile.close();
outfile.close();
Don’t wait for operating system to close
files at program end:
may be limit on number of open files
may be buffered output data waiting to send
to file

© Pearson Education Limited 2015


Letting the User Specify a Filename

In many cases, you will want the user to


specify the name of a file for the program
to open.
In C++ 11, you can pass a string object
as an argument to a file stream object’s
open member function.

© Pearson Education Limited 2015


Letting the User Specify a
Filename in Program 5-24

Continued…

© Pearson Education Limited 2015


Letting the User Specify a
Filename in Program 5-24

© Pearson Education Limited 2015


Using the c_str Member Function
in Older Versions of C++
Prior to C++ 11, the open member
function requires that you pass the name
of the file as a null-terminated string, which
is also known as a C-string.
String literals are stored in memory as
null-terminated C-strings, but string
objects are not.

© Pearson Education Limited 2015


Using the c_str Member Function
in Older Versions of C++
string objects have a member function named c_str
It returns the contents of the object formatted as a
null-terminated C-string.
Here is the general format of how you call the c_str
function:
stringObject.c_str()
Line 18 in Program 5-24 could be rewritten in the
following manner:

inputFile.open(filename.c_str());

© Pearson Education Limited 2015


5.12
Breaking and Continuing a Loop

© Pearson Education Limited 2015


Breaking Out of a Loop
Can use break to terminate execution of
a loop

Use sparingly if at all – makes code harder


to understand and debug

When used in an inner loop, terminates


that loop only and goes back to outer loop

© Pearson Education Limited 2015


The continue Statement
Can use continue to go to end of loop
and prepare for next repetition
while, do-while loops: go to test, repeat
loop if test passes
for loop: perform update step, then test,
then repeat loop if test passes
Use sparingly – like break, can make
program logic hard to follow

© Pearson Education Limited 2015

You might also like