Chapter 5 Loops and Files
5.1 The Increment and Decrement Operators
Concept:
++ and -- are operators that add and subtract 1 from their operands.
- Incrementing a value means increasing it by one.
- Decrementing a value means decreasing it by one.
- C++ provides the unary increment operator (
++) and decrement operator (--) for these tasks. - For example,
num++;incrementsnum, andnum--;decrementsnum.
Note:
The expression num++ is pronounced “num plus plus,” andnum-- is pronounced “num minus minus.”
- Postfix mode: The operator is placed after the variable (e.g.,
num++). - Prefix mode: The operator is placed before the variable (e.g.,
++num). - In simple statements, both modes achieve the same result of modifying the variable’s value by one.
🗊 Program 5-1
#include <iostream>
using namespace std;
int main()
{
int num = 4;
cout << "The variable num is " << num << endl;
cout << "I will now increment num.\n\n";
num++;
cout << "Now the variable num is " << num << endl;
cout << "I will increment num again.\n\n";
++num;
cout << "Now the variable num is " << num << endl;
cout << "I will now decrement num.\n\n";
num--;
cout << "Now the variable num is " << num << endl;
cout << "I will decrement num again.\n\n";
--num;
cout << "Now the variable num is " << num << endl;
return 0;
}💻 Program Output
The Difference between Postfix and Prefix Modes
- The difference between postfix and prefix modes becomes important when the operators are used in more complex statements.
- Postfix mode: The variable’s value is used in the expression first, and then it is incremented or decremented.
- Example: In
cout << num++;(wherenumis 4), the value 4 is displayed, and thennumis incremented to 5.
- Example: In
- Prefix mode: The variable is incremented or decremented first, and then its new value is used in the expression.
- Example: In
cout << ++num;(wherenumis 4),numis first incremented to 5, and then the value 5 is displayed.
- Example: In
🗊 Program 5-2
💻 Program Output
Consider the following code:
int x = 1; int y y = x++;In postfix mode, the value of
x(which is 1) is assigned toybeforexis incremented.After execution,
ywill be 1, andxwill be 2.Now consider prefix mode:
int x = 1; int y; y = ++x;In prefix mode,
xis incremented to 2 before its value is assigned toy.After execution, both
yandxwill be 2.
Using ++ and -- in Mathematical Expressions
These operators can be used within mathematical expressions, where the order of operations matters.
Consider this example:
a = 2; b = 5; c = a * b++; cout << a << " " << b << " " << c;cis assigneda * b(which is 10), and thenbis incremented. The output will be2 6 10.If the expression were
c = a * ++b;,bwould be incremented to 6 before the multiplication.cwould be assigned2 * 6(which is 12). The output would be2 6 12.The operand of
++and--must be an lvalue (something that identifies a memory location, like a variable). You cannot use it on an expression like(a * b).
Using ++ and -- in Relational Expressions
The operators can also be used in relational expressions, where the mode affects the outcome of the comparison.
Consider this code:
x = 10; if (x++ > 10) cout << "x is greater than 10.\n";In postfix mode, the comparison
10 > 10happens first (which is false), and thenxis incremented. Thecoutstatement will not execute.If prefix mode is used:
x = 10; if (++x > 10) cout << "x is greater than 10.\n";xis first incremented to 11, and then the comparison11 > 10is performed (which is true). Thecoutstatement will execute.
Checkpoint
5.1 What will the following program segments display?
x = 2; y = x++; cout << x << y;x = 2; y = ++x; cout << x << y;x = 2; y = 4; cout << x++ << --y;x = 2; y = 2 * x++; cout << x << y;x = 99; if (x++ < 100) cout "It is true!\n"; else cout << "It is false!\n";x = 0; if (++x) cout << "It is true!\n"; else cout << "It is false!\n";
5.2 Introduction to Loops: The while Loop
Concept:
A loop is part of a program that repeats.
The while Loop
- A loop is a control structure that causes a statement or group of statements to repeat.
- C++ offers three looping structures:
while,do-while, andfor. They differ in how they control repetition.
The while Loop
A
whileloop has two main parts:- An expression that is tested for a true or false value.
- A statement or block that is repeated as long as the expression is true.
Here is the general format:
while (expression) statement;To repeat a block of statements, use braces:
while (expression) { statement; statement; }How it works:
- The
expressionis tested. - If the expression is true, the loop body (the statement or block) is executed.
- This cycle repeats until the
expressionbecomes false.
- The
🗊 Program 5-3
💻 Program Output
- Each repetition of a loop is called an iteration.
- In Program 5-3, the loop performs five iterations.
- The variable
numberis the loop control variable because it controls the number of times the loop iterates.
The while Loop Is a Pretest Loop
- The
whileloop is a pretest loop, meaning it tests its expression before each iteration. - If the test expression is false initially, the loop will never execute.
- To ensure a
whileloop runs at least once, you must initialize the relevant data so the test expression is true from the start.
Infinite Loops
Loops must contain a mechanism to terminate. Something inside the loop must eventually make the test expression false.
An infinite loop continues to repeat until the program is interrupted.
This happens if the loop lacks a way to alter the loop control variable.
int number = 0; while (number < 5) { cout << "Hello\n"; }Accidentally placing a semicolon after the
whileheader also creates an infinite loop with a null statement as its body.while (number < 5);
Don’t Forget the Braces with a Block of Statements
If you intend for a loop to repeat a block of statements, you must enclose them in braces
{}.Without braces, the
whilestatement only controls the single statement immediately following it, which can lead to infinite loops.while (number < 5) cout << "Hello\n"; number++;
Programming Style and the while Loop
- For good programming style, the body of the loop should be indented.
- If the body is a single statement, place it on the line after the
whileheader. - If the body is a block, indent each statement within the braces. This makes the code more readable.
In the Spotlight:
Designing a Program with a while Loop
A project currently underway at Chemical Labs, Inc. requires that a substance be continually heated in a vat. A technician must check the substance’s temperature every 15 minutes. If the substance’s temperature does not exceed 102.5 degrees Celsius, then the technician does nothing. However, if the temperature is greater than 102.5 degrees Celsius, the technician must turn down the vat’s thermostat, wait 5 minutes, and check the temperature again. The technician repeats these steps until the temperature does not exceed 102.5 degrees Celsius. The director of engineering has asked you to write a program that guides the technician through this process.
Here is the algorithm:
Prompt the user to enter the substance’s temperature.
Repeat the following steps as long as the temperature is greater than 102.5 degrees Celsius:
Tell the technician to turn down the thermostat, wait 5 minutes, and check the temperature again.
Prompt the user to enter the substance’s temperature.
After the loop finishes, tell the technician that the temperature is acceptable and to check it again in 15 minutes.
After reviewing this algorithm, you realize that steps 2a and 2b should not be performed if the test condition (temperature is greater than 102.5) is false to begin with. The while loop will work well in this situation, because it will not execute even once if its condition is false. Program 5-4 shows the code for the program.
🗊 Program 5-4
#include <iostream>
using namespace std;
int main()
{
const double MAX_TEMP = 102.5;
double temperature;
cout << "Enter the substance's Celsius temperature: ";
cin >> temperature;
while (temperature > MAX_TEMP)
{
cout << "The temperature is too high. Turn the\n";
cout << "thermostat down and wait 5 minutes.\n";
cout << "Then take the Celsius temperature again\n";
cout << "and enter it here: ";
cin >> temperature;
}
cout << "The temperature is acceptable.\n";
cout << "Check it again in 15 minutes.\n";
return 0;
}💻 Program Output
5.3 Using the while Loop for Input Validation
Concept:
The while loop can be used to create input routines that repeat until acceptable data is entered.
Input validation is the process of inspecting user-provided data to determine if it’s valid.
The phrase “garbage in, garbage out” highlights the importance of ensuring a program receives good input to produce good output.
A
whileloop is excellent for input validation. If the input is invalid, the loop can prompt the user to re-enter the data until a valid value is provided.Example validation loop for a number between 1 and 100:
cout << "Enter a number in the range 1-100: "; cin >> number; while (number < 1 || number > 100) { cout << "ERROR: Enter a value in the range 1-100: "; cin >> number; }The initial read operation before the loop is known as a priming read. It provides the first value for the loop to test.
🗊 Program 5-5
#include <iostream>
using namespace std;
int main()
{
const int MIN_PLAYERS = 9,
MAX_PLAYERS = 15;
int players,
teamPlayers,
numTeams,
leftOver;
cout << "How many players do you wish per team? ";
cin >> teamPlayers;
while (teamPlayers < MIN_PLAYERS || teamPlayers > MAX_PLAYERS)
{
cout << "You should have at least " << MIN_PLAYERS
<< " but no more than " << MAX_PLAYERS << " per team.\n";
cout << "How many players do you wish per team? ";
cin >> teamPlayers;
}
cout << "How many players are available? ";
cin >> players;
while (players <= 0)
{
cout << "Please enter 0 or greater: ";
cin >> players;
}
numTeams = players / teamPlayers;
leftOver = players % teamPlayers;
cout << "There will be " << numTeams << " teams with "
<< leftOver << " players left over.\n";
return 0;
}💻 Program Output
Checkpoint
5.2 Write an input validation loop that asks the user to enter a number in the range of 10 through 25.
5.3 Write an input validation loop that asks the user to enter ‘Y’, ‘y’, ‘N’, or ‘n’.
5.4 Write an input validation loop that asks the user to enter “Yes” or “No”.
5.4 Counters
Concept:
A counter is a variable that is regularly incremented or decremented each time a loop iterates.
- A counter is a variable used to keep track of the number of loop iterations.
- It is typically initialized before the loop and incremented or decremented within the loop body.
- This allows a program to control a loop to execute a specific number of times.
🗊 Program 5-6
💻 Program Output
- In Program 5-6, the
numvariable serves as a counter. - It starts at 1 and is incremented in each iteration.
- The loop terminates when
numreaches 11. - Proper initialization of a counter variable is crucial.
Note:
It’s important that num be properly initialized. Remember, variables defined inside a function have no guaranteed starting value.
5.5 The do-while Loop
Concept:
The do-while loop is a posttest loop, which means its expression is tested after each iteration.
The
do-whileloop is like an invertedwhileloop.It is a posttest loop, meaning the expression is tested after the loop body has executed.
This guarantees that the
do-whileloop will always perform at least one iteration, even if the expression is initially false.Format for a single statement:
do statement; while (expression);Format for a block of statements:
do { statement; statement; } while (expression);
Note:
The do-while loop must be terminated with a semicolon.
- Use a
do-whileloop when you want to ensure the loop executes at least once. - Program 5-7 demonstrates a user-controlled loop, where the user decides whether to repeat the process.
🗊 Program 5-7
#include <iostream>
using namespace std;
int main()
{
int score1, score2, score3;
double average;
char again;
do
{
cout << "Enter 3 scores and I will average them: ";
cin >> score1 >> score2 >> score3;
average = (score1 + score2 + score3) / 3.0;
cout << "The average is " << average << ".\n";
cout << "Do you want to average another set? (Y/N) ";
cin >> again;
} while (again == 'Y' || again == 'y');
return 0;
}💻 Program Output
5.6 The for Loop
Concept:
The for loop is ideal for performing a known number of iterations.
- Loops can be categorized as conditional or count-controlled.
- A conditional loop executes as long as a condition is true (e.g.,
while). - A count-controlled loop repeats a specific number of times.
- A conditional loop executes as long as a condition is true (e.g.,
The for Loop
A count-controlled loop requires three elements:
- Initialization of a counter variable.
- A test of the counter against a maximum value.
- An update (usually incrementing) of the counter in each iteration.
The
forloop is specifically designed for count-controlled situations.Format for a single statement:
for (initialization; test; update) statement;Format for a block:
for (initialization; test; update) { statement; }The loop header contains three expressions separated by semicolons:
- The initialization expression runs once at the beginning.
- The test expression is evaluated before each iteration. The loop continues as long as it’s true.
- The update expression executes at the end of each iteration.
🗊 Program 5-9
💻 Program Output
Using the for Loop instead of while or do-while
- The
forloop is the best choice when a loop requires an initialization, a test condition to stop, and an update at the end of each iteration. - Many
whileloops that use a counter can be easily converted intoforloops, making the code more compact and readable.
The for Loop Is a Pretest Loop
- Like the
whileloop, theforloop is a pretest loop. - It evaluates the test expression before each iteration.
- If the test expression is initially false, the loop will not execute at all.
Avoid Modifying the Counter Variable in the Body of the for Loop
- All updates to the loop’s counter variable should be done in the update expression of the loop header.
- Modifying the counter variable inside the loop’s body can lead to unexpected behavior and logical errors.
Other Forms of the Update Expression
- The update expression is not limited to simple increments (
++). - You can use other expressions, such as
num += 2to count by twos, ornum--to count backward.
Defining a Variable in the for Loop’s Initialization Expression
You can define the counter variable directly within the
forloop’s initialization expression.for (int num = 1; num <= 10; num++) cout << num << endl;When a variable is defined this way, its scope is limited to the loop. It cannot be accessed outside the loop.
Creating a User-Controlled for Loop
- The starting and ending values for the counter variable can be provided by the user, allowing them to control the number of iterations.
🗊 Program 5-10
#include <iostream>
using namespace std;
int main()
{
int minNumber,
maxNumber;
cout << "I will display a table of numbers and "
<< "their squares.\n"
<< "Enter the starting number: ";
cin >> minNumber;
cout << "Enter the ending number: ";
cin >> maxNumber;
cout << "Number Number Squared\n"
<< "-------------------------\n";
for (int num = minNumber; num <= maxNumber; num++)
cout << num << "\t\t" << (num * num) << endl;
return 0;
}💻 Program Output
Using Multiple Statements in the Initialization and Update Expressions
- You can execute multiple statements in the initialization and update expressions by separating them with commas.
- Example:
for (x = 1, y = 1; x <= 5; x++, y++) - This technique does not apply to the test expression; for multiple conditions there, use logical operators like
&&or||.
Omitting the for Loop’s Expressions
Any of the three expressions in the
forloop header can be omitted.If the initialization is done before the loop, it can be left blank.
If the update is handled inside the loop body, it can be left blank.
Omitting the test expression creates an infinite loop by default.
for ( ; ; ) cout << "Hello World\n";
In the Spotlight:
Designing a Count-Controlled Loop with the for Statement
Your friend Amanda just inherited a European sports car from her uncle. Amanda lives in the United States, and she is afraid she will get a speeding ticket because the car’s speedometer indicates kilometers per hour. She has asked you to write a program that displays a table of speeds in kilometers per hour with their values converted to miles per hour. The formula for converting kilometers per hour to miles per hour is:
MPH = KPH\,*\, 0.6214
In the formula, MPH is the speed in miles per hour and KPH is the speed in kilometers per hour.
The table your program displays should show speeds from 60 kilometers per hour through 130 kilometers per hour, in increments of 10, along with their values converted to miles per hour. The table should look something like this:
| KPH | MPH |
|---|---|
| 60 | 37.3 |
| 70 | 43.5 |
| 80 | 49.7 |
| ⋮ | |
| 130 | 80.8 |
After thinking about this table of values, you decide that you will write a for loop that uses a counter variable to hold the kilometer-per-hour speeds. The counter’s starting value will be 60, its ending value will be 130, and you will add 10 to the counter variable after each iteration. Inside the loop, you will use the counter variable to calculate a speed in miles per hour. Program 5-11 shows the code.
🗊 Program 5-11
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int START_KPH = 60,
END_KPH = 130,
INCREMENT = 10;
const double CONVERSION_FACTOR = 0.6214;
int kph;
double mph;
cout << fixed << showpoint << setprecision(1);
cout << "KPH\tMPH\n";
cout << "---------------\n";
for (kph = START_KPH; kph <= END_KPH; kph += INCREMENT)
{
mph = kph * CONVERSION_FACTOR;
cout << kph << "\t" << mph << endl;
}
return 0;
}💻 Program Output
Checkpoint
5.6 Name the three expressions that appear inside the parentheses in the
forloop’s header.5.7 You want to write a
forloop that displays “I love to program” 50 times. Assume you will use a counter variable namedcount.What initialization expression will you use?
What test expression will you use?
What update expression will you use?
Write the loop.
5.8 What will the following program segments display?
for (int count = 0; count < 6; count++) cout << (count + count);for (int value = -5; value < 5; value++) cout << value;int x; for (x = 5; x <= 14; x += 3) cout << x << endl; cout << x << endl;
5.9 Write a
forloop that displays your name 10 times.5.10 Write a
forloop that displays all of the odd numbers, 1 through 49.5.11 Write a
forloop that displays every fifth number, 0 through 100.
5.7 Keeping a Running Total
Concept:
A running total is a sum of numbers that accumulates with each iteration of a loop. The variable used to keep the running total is called an accumulator.
Many programming tasks involve calculating the sum of a series of numbers.
This is typically achieved using two elements:
- A loop to read each number in the series.
- A variable, known as an accumulator, to hold the accumulating sum.
The process of accumulating a sum within a loop is often called keeping a running total.
The logic is as follows:
- Initialize the accumulator variable to 0. This is a critical step.
- Inside a loop, read a number.
- Add the number to the accumulator.
- Repeat steps 2 and 3 for all numbers.
When the loop finishes, the accumulator will hold the total sum.
🗊 Program 5-12
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int days;
double total = 0.0;
cout << "For how many days do you have sales amounts? ";
cin >> days;
for (int count = 1; count <= days; count++)
{
double sales;
cout << "Enter the sales for day " << count << ": ";
cin >> sales;
total += sales;
}
cout << fixed << showpoint << setprecision(2);
cout << "The total sales are $" << total << endl;
return 0;
}💻 Program Output
5.8 Sentinels
Concept:
A sentinel is a special value that marks the end of a list of values.
- Sometimes a user doesn’t know the number of items they will enter in advance.
- In these cases, a sentinel value can be used to signal the end of the input.
- A sentinel is a special value that cannot be mistaken for a valid data item.
- When the program reads the sentinel value, the loop terminates.
- This technique avoids the need to count the items beforehand.
🗊 Program 5-13
#include <iostream>
using namespace std;
int main()
{
int game = 1,
points,
total = 0;
cout << "Enter the number of points your team has earned\n";
cout << "so far in the season, then enter -1 when finished.\n\n";
cout << "Enter the points for game " << game << ": ";
cin >> points;
while (points != -1)
{
total += points;
game++;
cout << "Enter the points for game " << game << ": ";
cin >> points;
}
cout << "\nThe total points are " << total << endl;
return 0;
}💻 Program Output
- In Program 5-13, -1 is chosen as the sentinel because a team cannot score negative points.
- A priming read is used before the loop to get the first value, allowing the loop to terminate immediately if the first input is the sentinel.
- The sentinel value itself is not included in the running total.
Checkpoint
5.12 Write a
forloop that repeats seven times, asking the user to enter a number. The loop should also calculate the sum of the numbers entered.5.13 In the following program segment, which variable is the counter variable and which is the accumulator?
int a, x, y = 0; for (x = 0; x < 10; x++) { cout << "Enter a number: "; cin >> a; y += a; } cout << "The sum of those numbers is " << y << endl;5.14 Why should you be careful when choosing a sentinel value?
5.15 How would you modify Program 5-13 so any negative value is a sentinel?
5.9 Focus on Software Engineering: Deciding Which Loop to Use
Concept:
Although most repetitive algorithms can be written with any of the three types of loops, each works best in different situations.
The
whileloop:- A conditional, pretest loop.
- Ideal when you don’t want the loop to iterate if the condition is initially false.
- Good for input validation and reading data lists terminated by a sentinel.
The
do-whileloop:- A conditional, posttest loop.
- Ideal when you always want the loop to iterate at least once.
- A good choice for repeating a menu.
The
forloop:- A pretest loop with built-in initialization, testing, and updating expressions.
- Ideal for count-controlled situations where the exact number of iterations is known.
5.10 Nested Loops
Concept:
A loop that is inside another loop is called a nested loop.
A nested loop is a loop that is contained within the body of another loop.
The inner loop executes all of its iterations for each single iteration of the outer loop.
A clock is a good analogy: for every one-hour tick (outer loop), the minute hand ticks 60 times (inner loop).
Key points about nested loops:
- An inner loop completes its full cycle for each iteration of an outer loop.
- Inner loops iterate more rapidly than outer loops.
- The total number of iterations is the product of the iterations of all the loops (e.g., an outer loop of 10 and inner loop of 5 gives 50 total inner loop iterations).
🗊 Program 5-14
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int numStudents,
numTests;
double total,
average;
cout << fixed << showpoint << setprecision(1);
cout << "This program averages test scores.\n";
cout << "For how many students do you have scores? ";
cin >> numStudents;
cout << "How many test scores does each student have? ";
cin >> numTests;
for (int student = 1; student <= numStudents; student++)
{
total = 0;
for (int test = 1; test <= numTests; test++)
{
double score;
cout << "Enter score " << test << " for ";
cout << "student " << student << ": ";
cin >> score;
total += score;
}
average = total / numTests;
cout << "The average score for student " << student;
cout << " is " << average << ".\n\n";
}
return 0;
}💻 Program Output
5.11 Using Files for Data Storage
Concept:
When a program needs to save data for later use, it writes the data in a file. The data can then be read from the file at a later time.
Data stored in variables (in RAM) is lost when a program stops running.
To retain data, programs save it in a file, which is usually stored on a computer’s disk.
This allows data to be retrieved and used at a later time.
Writing data: The process of saving data from a variable in RAM to a file. The file being written to is an output file.
Reading data: The process of retrieving data from a file and copying it into a variable in RAM. The file being read from is an input file.
The three fundamental steps of file processing are:
- Open the file: This creates a connection between the program and the file.
- Process the file: Data is either written to or read from the file.
- Close the file: This disconnects the file from the program.
Types of Files
- Text file: Contains data encoded as text (e.g., ASCII or Unicode). It can be viewed in a simple text editor.
- Binary file: Contains data that has not been converted to text. It cannot be viewed correctly with a text editor.
File Access Methods
- Sequential access: Data is accessed from the beginning of the file to the end, in order. To get to data at the end, you must read all the data before it.
- Random access (or direct access): You can jump directly to any piece of data in the file without reading the preceding data.
Filenames and File Stream Objects
- Files on a disk are identified by a filename, which may include an extension (e.g.,
.txt,.jpg). - To work with a file, a C++ program uses a file stream object.
- This object is associated with a specific file and acts like
cinandcoutbut for files instead of the console.
Setting Up a Program for File Input/Output
To perform file operations, you must include the
<fstream>header file.#include <fstream>The
<fstream>header defines several data types for file stream objects.
| File Stream Data Type | Description |
|---|---|
ofstream |
Output file stream. You create an object of this data type when you want to create a file and write data to it. |
ifstream |
Input file stream. You create an object of this data type when you want to open an existing file and read data from it. |
fstream |
File stream. Objects of this data type can be used to open files for reading, writing, or both. |
Creating a File Object and Opening a File
First, a file stream object must be created.
Then, the file must be opened and linked to that object using the
openmember function.To open a file for input (reading):
ifstream inputFile; inputFile.open("Customers.txt");To open a file for output (writing):
ofstream outputFile; outputFile.open("Employees.txt");Important: Opening a file with an
ofstreamobject will create the file. If the file already exists, its contents will be erased.You can also define the object and open the file in a single statement:
ifstream inputFile("Customers.txt"); ofstream outputFile("Employees.txt");
Closing a File
It is good practice to explicitly close files using the
closemember function when you are finished with them.inputFile.close();Reasons to close files:
- It ensures any data held in an operating system buffer is written to the file.
- It frees up operating system resources.
Writing Data to a File
The stream insertion operator (
<<) is used withofstreamobjects to write data to a file, just as it is used withcoutto write to the screen.outputFile << "Price: " << price << endl;Using
endlor the\ncharacter writes a newline to the file, which separates items onto different lines.
🗊 Program 5-15
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outputFile;
outputFile.open("demofile.txt");
cout << "Now writing data to the file.\n";
outputFile << "Bach\n";
outputFile << "Beethoven\n";
outputFile << "Mozart\n";
outputFile << "Schubert\n";
outputFile.close();
cout << "Done.\n";
return 0;
}Program Screen Output
🗊 Program 5-16
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outputFile;
outputFile.open("demofile.txt");
cout << "Now writing data to the file.\n";
outputFile << "Bach";
outputFile << "Beethoven";
outputFile << "Mozart";
outputFile << "Schubert";
outputFile.close();
cout << "Done.\n";
return 0;
}Program Screen Output
🗊 Program 5-17
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outputFile;
int number1, number2, number3;
outputFile.open("Numbers.txt");
cout << "Enter a number: ";
cin >> number1;
cout << "Enter another number: ";
cin >> number2;
cout << "One more time. Enter a number: ";
cin >> number3;
outputFile << number1 << endl;
outputFile << number2 << endl;
outputFile << number3 << endl;
cout << "The numbers were saved to a file.\n";
outputFile.close();
cout << "Done.\n";
return 0;
}Program Screen Output with Example Input Shown in Bold
🗊 Program 5-18
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream outputFile;
string name1, name2, name3;
outputFile.open("Friends.txt");
cout << "Enter the names of three friends.\n";
cout << "Friend #1: ";
cin >> name1;
cout << "Friend #2: ";
cin >> name2;
cout << "Friend #3: ";
cin >> name3;
outputFile << name1 << endl;
outputFile << name2 << endl;
outputFile << name3 << endl;
cout << "The names were saved to a file.\n";
outputFile.close();
return 0;
}Program Screen Output with Example Input Shown in Bold
Reading Data from a File
The stream extraction operator (
>>) is used withifstreamobjects to read data from a file into variables.inputFile >> name;
Reading Data from a File
🗊 Program 5-19
#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";
inputFile >> name;
cout << name << endl;
inputFile >> name;
cout << name << endl;
inputFile >> name;
cout << name << endl;
inputFile.close();
return 0;
}💻 Program Output
The Read Position
- An
ifstreamobject maintains a read position, which marks the location of the next byte to be read from the file. - When a file is first opened, the read position is at the beginning of the file.
- As data is read, the read position automatically advances through the file.
- The
>>operator reads data up to the next whitespace character (space, tab, or newline).
Reading Numeric Data from a Text File
- Even when a text file contains numbers, they are stored as characters (e.g., “100”).
- When you use the
>>operator to read from a text file into a numeric variable (like anintordouble), it automatically converts the character representation into the appropriate numeric data type.
🗊 Program 5-20
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
int value1, value2, value3, sum;
inFile.open("NumericData.txt");
inFile >> value1;
inFile >> value2;
inFile >> value3;
inFile.close();
sum = value1 + value2 + value3;
cout << "Here are the numbers:\n"
<< value1 << " " << value2
<< " " << value3 << endl;
cout << "Their sum is: " << sum << endl;
return 0;
}💻 Program Output
Using Loops to Process Files
- Loops are essential for processing files that contain large amounts of data.
- A loop can be used to read or write multiple items to a file without writing repetitive code.
🗊 Program 5-21
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outputFile;
int numberOfDays;
double sales;
cout << "For how many days do you have sales? ";
cin >> numberOfDays;
outputFile.open("Sales.txt");
for (int count = 1; count <= numberOfDays; count++)
{
cout << "Enter the sales for day "
<< count << ": ";
cin >> sales;
outputFile << sales << endl;
}
outputFile.close();
cout << "Data written to Sales.txt\n";
return 0;
}💻 Program Output
Detecting the End of the File
A program must know when it has reached the end of a file to avoid errors from trying to read past it.
The stream extraction operator
>>can be used to detect the end of a file. When used as a Boolean expression, it returnstrueif a value was successfully read, andfalseif it failed (e.g., at the end of the file).This allows for a simple
whileloop structure to read all the data in a file:while (inputFile >> number) { }The loop will automatically terminate when there is no more data to read.
Testing for File Open Errors
The
openfunction can fail (e.g., if an input file does not exist).You should always test whether a file was opened successfully before attempting to process it.
You can test the file stream object itself in an
ifstatement. It evaluates totrueif the last operation (likeopen) was successful andfalseif it failed.inputFile.open("info.txt"); if (inputFile) { } else { }Alternatively, you can use the
.fail()member function, which returnstrueif an operation failed.
🗊 Program 5-23
💻 Program Output
Letting the User Specify a Filename
- Instead of hard-coding a filename as a string literal, you can prompt the user to enter a filename.
- The user’s input can be stored in a
stringobject, which can then be passed to theopenmember function (in C++11 and later).
🗊 Program 5-24
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile;
string filename;
int number;
cout << "Enter the filename: ";
cin >> filename;
inputFile.open(filename);
if (inputFile)
{
while (inputFile >> number)
{
cout << number << endl;
}
inputFile.close();
}
else
{
cout << "Error opening the file.\n";
}
return 0;
}💻 Program Output
Using the c_str Member Function in Older Versions of C++
In versions of C++ prior to C++11, the
openfunction requires a C-style, null-terminated string, not astringobject.The
stringobject’sc_str()member function can be used to get a C-string representation of its contents.This provides compatibility with older compilers.
inputFile.open(filename.c_str());
Checkpoint
5.16 What is an output file? What is an input file?
5.17 What three steps must be taken when a file is used by a program?
5.18 What is the difference between a text file and a binary file?
5.19 What is the difference between sequential access and random access?
5.20 What type of file stream object do you create if you want to write data to a file?
5.21 What type of file stream object do you create if you want to read data from a file?
5.22 Write a short program that uses a
forloop to write the numbers 1 through 10 to a file.5.23 Write a short program that opens the file created by the program you wrote for Checkpoint 5.22, reads all of the numbers from the file, and displays them.
5.12 Optional Topics: Breaking and Continuing a Loop
Concept:
The break statement causes a loop to terminate early. The continue statement causes a loop to stop its current iteration and begin the next one.
Warning!
Use the break and continue statements with great caution. Because they bypass the normal condition that controls the loop’s iterations, these statements make code difficult to understand and debug. For this reason, you should avoid using break and continue whenever possible. However, because they are part of the C++ language, we discuss them briefly in this section.
The
breakstatement causes a loop to terminate immediately.Program execution jumps to the statement immediately following the loop.
The
continuestatement causes the current iteration of a loop to stop immediately.Execution then jumps to the start of the next iteration.
- In a
whileordo-whileloop, it jumps to the test expression. - In a
forloop, it jumps to the update expression, and then the test expression is evaluated.
- In a
🗊 Program 5-25
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double value;
char choice;
cout << "Enter a number: ";
cin >> value;
cout << "This program will raise " << value;
cout << " to the powers of 0 through 10.\n";
for (int count = 0; count <= 10; count++)
{
cout << value << " raised to the power of ";
cout << count << " is " << pow(value, count);
cout << "\nEnter Q to quit or any other key ";
cout << "to continue. ";
cin >> choice;
if (choice == 'Q' || choice == 'q')
break;
}
return 0;
}💻 Program Output
Using break in a Nested Loop
- In a nested loop, a
breakstatement only terminates the inner loop it is placed in. - The outer loop will continue its iterations as normal.
The continue Statement
- The
continuestatement skips the remainder of the current loop iteration and proceeds to the next one. - Any statements in the loop body that appear after the
continuestatement are ignored for that iteration.
🗊 Program 5-26
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int dvdCount = 1;
int numDVDs;
double total = 0.0;
char current;
cout << "How many DVDs are being rented? ";
cin >> numDVDs;
do
{
if ((dvdCount % 3) == 0)
{
cout << "DVD #" << dvdCount << " is free!\n";
continue;
}
cout << "Is DVD #" << dvdCount;
cout << " a current release? (Y/N) ";
cin >> current;
if (current == 'Y' || current == 'y')
total += 3.50;
else
total += 2.50;
} while (dvdCount++ < numDVDs);
cout << fixed << showpoint << setprecision(2);
cout << "The total is $" << total << endl;
return 0;
}💻 Program Output
Case Study: See the Loan Amortization Case Study on the Computer Science Portal at www.pearsonhighered.com/gaddis.
Review Questions and Exercises
Short Answer
Why should you indent the statements in the body of a loop?
Describe the difference between pretest loops and posttest loops.
Why are the statements in the body of a loop called conditionally executed statements?
What is the difference between the
whileloop and thedo-whileloop?Which loop should you use in situations where you wish the loop to repeat until the test expression is false, and the loop should not execute if the test expression is false to begin with?
Which loop should you use in situations where you wish the loop to repeat until the test expression is false, but the loop should execute at least one time?
Which loop should you use when you know the number of required iterations?
Why is it critical that counter variables be properly initialized?
Why is it critical that accumulator variables be properly initialized?
Why should you be careful not to place a statement in the body of a
forloop that changes the value of the loop’s counter variable?What header file do you need to include in a program that performs file operations?
What data type do you use when you want to create a file stream object that can write data to a file?
What data type do you use when you want to create a file stream object that can read data from a file?
Why should a program close a file when it’s finished using it?
What is a file’s read position? Where is the read position when a file is first opened for reading?
Fill-in-the-Blank
To __________ a value means to increase it by one, and to __________ a value means to decrease it by one.
When the increment or decrement operator is placed before the operand (or to the operand’s left), the operator is being used in __________ mode.
When the increment or decrement operator is placed after the operand (or to the operand’s right), the operator is being used in __________ mode.
The statement or block that is repeated is known as the __________ of the loop.
Each repetition of a loop is known as a(n) __________.
A loop that evaluates its test expression before each repetition is a(n) __________ loop.
A loop that evaluates its test expression after each repetition is a(n) __________ loop.
A loop that does not have a way of stopping is a(n) __________ loop.
A(n) __________ is a variable that “counts” the number of times a loop repeats.
A(n) __________ is a sum of numbers that accumulates with each iteration of a loop.
A(n) __________ is a variable that is initialized to some starting value, usually zero, then has numbers added to it in each iteration of a loop.
A(n) __________ is a special value that marks the end of a series of values.
The __________ loop always iterates at least once.
The __________ and __________ loops will not iterate at all if their test expressions are false to start with.
The __________ loop is ideal for situations that require a counter.
Inside the
forloop’s parentheses, the first expression is the __________, the second expression is the __________, and the third expression is the __________.A loop that is inside another is called a(n) __________ loop.
The __________ statement causes a loop to terminate immediately.
The __________ statement causes a loop to skip the remaining statements in the current iteration.
Algorithm Workbench
Write a
whileloop that lets the user enter a number. The number should be multiplied by 10, and the result stored in the variableproduct. The loop should iterate as long asproductcontains a value less than 100.Write a
do-whileloop that asks the user to enter two numbers. The numbers should be added and the sum displayed. The user should be asked if he or she wishes to perform the operation again. If so, the loop should repeat; otherwise, it should terminate.Write a
forloop that displays the following set of numbers:0, 10, 20, 30, 40, 50 . . . 1000Write a loop that asks the user to enter a number. The loop should iterate 10 times and keep a running total of the numbers entered.
Write a nested loop that displays 10 rows of ‘#’ characters. There should be 15 ‘#’ characters in each row.
Convert the following
whileloop to ado-whileloop:int x = 1; while (x > 0) { cout << "enter a number: "; cin >> x; }Convert the following
do-whileloop to awhileloop:char sure; do { cout << "Are you sure you want to quit? "; cin >> sure; } while (sure != 'Y' && sure != 'N');Convert the following
whileloop to aforloop:int count = 0; while (count < 50) { cout << "count is " << count << endl; count++; }Convert the following
forloop to awhileloop:for (int x = 50; x > 0; x--) { cout << x << " seconds to go.\n"; }Write code that does the following: Opens an output file with the filename Numbers.txt, uses a loop to write the numbers 1 through 100 to the file, then closes the file.
Write code that does the following: Opens the Numbers.txt file that was created by the code you wrote in Question 44, reads all of the numbers from the file and displays them, then closes the file.
Modify the code that you wrote in Question 45 so it adds all of the numbers read from the file and displays their total.
True or False
T F The operand of the increment and decrement operators can be any valid mathematical expression.
T F The
coutstatement in the following program segment will display 5:int x = 5; cout << x++;T F The
coutstatement in the following program segment will display 5:int x = 5; cout << ++x;T F The
whileloop is a pretest loop.T F The
do-whileloop is a pretest loop.T F The
forloop is a posttest loop.T F It is not necessary to initialize counter variables.
T F All three of the
forloop’s expressions may be omitted.T F One limitation of the
forloop is that only one variable may be initialized in the initialization expression.T F Variables may be defined inside the body of a loop.
T F A variable may be defined in the initialization expression of the
forloop.T F In a nested loop, the outer loop executes faster than the inner loop.
T F In a nested loop, the inner loop goes through all of its iterations for every single iteration of the outer loop.
T F To calculate the total number of iterations of a nested loop, add the number of iterations of all the loops.
T F The
breakstatement causes a loop to stop the current iteration and begin the next one.T F The
continuestatement causes a terminated loop to resume.T F In a nested loop, the
breakstatement only interrupts the loop in which it is placed.T F When you call an
ofstreamobject’sopenmember function, the specified file will be erased if it already exists.
Find the Errors
Each of the following programs has errors. Find as many as you can.
-
#include <iostream> using namespace std; int main() { int num1 = 0, num2 = 10, result; num1++; result = ++(num1 + num2); cout << num1 << " " << num2 << " " << result; return 0; } -
#include <iostream> using namespace std; int main() { int num1, num2; char again; while (again == 'y' || again == 'Y') cout << "Enter a number: "; cin >> num1; cout << "Enter another number: "; cin >> num2; cout << "Their sum is << (num1 + num2) << endl; cout << "Do you want to do this again? "; cin >> again; return 0; } -
#include <iostream> using namespace std; int main() { int num, bigNum, power, count; cout << "Enter an integer: "; cin >> num; cout << "What power do you want it raised to? "; cin >> power; bigNum = num; while (count++ < power); bigNum *= num; cout << "The result is << bigNum << endl; return 0; } -
#include <iostream> using namespace std; int main() { int numCount, total; double average; cout << "How many numbers do you want to average? "; cin >> numCount; for (int count = 0; count < numCount; count++) { int num; cout << "Enter a number: "; cin >> num; total += num; count++; } average = total / numCount; cout << "The average is << average << endl; return 0; } -
#include <iostream> using namespace std; int main() { int choice, num1, num2; do { cout << "Enter a number: "; cin >> num1; cout << "Enter another number: "; cin >> num2; cout << "Their sum is " << (num1 + num2) << endl; cout << "Do you want to do this again?\n"; cout << "1 = yes, 0 = no\n"; cin >> choice; } while (choice = 1) return 0; } -
#include <iostream> using namespace std; int main() { int count = 1, total; while (count <= 100) total += count; cout << "The sum of the numbers 1-100 is "; cout << total << endl; return 0; }
Programming Challenges
Sum of Numbers
Write a program that asks the user for a positive integer value. The program should use a loop to get the sum of all the integers from 1 up to the number entered. For example, if the user enters 50, the loop will find the sum of 1, 2, 3, 4, . . ., 50.
Input Validation: Do not accept a negative starting number.
Characters for the ASCII Codes
Write a program that uses a loop to display the characters for the ASCII codes 0 through 127. Display 16 characters on each line.
Ocean Levels
Assuming the ocean’s level is currently rising at about 1.5 millimeters per year, write a program that displays a table showing the number of millimeters that the ocean will have risen each year for the next 25 years.
Calories Burned
Running on a particular treadmill you burn 3.6 calories per minute. Write a program that uses a loop to display the number of calories burned after 5, 10, 15, 20, 25, and 30 minutes.

Solving the Calories Burned Problem
Membership Fees Increase
A country club, which currently charges $2,500 per year for membership, has announced it will increase its membership fee by 4 percent each year for the next 6 years. Write a program that uses a loop to display the projected rates for the next 6 years.
Distance Traveled
The distance a vehicle travels can be calculated as follows:
distance = speed * timeFor example, if a train travels 40 miles per hour for 3 hours, the distance traveled is 120 miles.
Write a program that asks the user for the speed of a vehicle (in miles per hour) and how many hours it has traveled. The program should then use a loop to display the distance the vehicle has traveled for each hour of that time period. Here is an example of the output:
What is the speed of the vehicle in mph? 40 How many hours has it traveled? 3 Hour Distance Traveled -------------------------------- 1 40 2 80 3 120Input Validation: Do not accept a negative number for speed and do not accept any value less than 1 for time traveled.
Pennies for Pay
Write a program that calculates how much a person would earn over a period of time if his or her salary is one penny the first day and two pennies the second day, and continues to double each day. The program should ask the user for the number of days. Display a table showing how much the salary was for each day, and then show the total pay at the end of the period. The output should be displayed in a dollar amount, not the number of pennies.
Input Validation: Do not accept a number less than 1 for the number of days worked.
Math Tutor
This program started in Programming Challenge 17, of Chapter 3, and was modified in Programming Challenge 11 of Chapter 4. Modify the program again so it displays a menu allowing the user to select an addition, subtraction, multiplication, or division problem. The final selection on the menu should let the user quit the program. After the user has finished the math problem, the program should display the menu again. This process is repeated until the user chooses to quit the program.
Input Validation: If the user selects an item not on the menu, display an error message and display the menu again.
Hotel Occupancy
Write a program that calculates the occupancy rate for a hotel. The program should start by asking the user how many floors the hotel has. A loop should then iterate once for each floor. In each iteration, the loop should ask the user for the number of rooms on the floor and how many of them are occupied. After all the iterations, the program should display how many rooms the hotel has, how many of them are occupied, how many are unoccupied, and the percentage of rooms that are occupied. The percentage may be calculated by dividing the number of rooms occupied by the number of rooms.
Note:It is traditional that most hotels do not have a thirteenth floor. The loop in this program should skip the entire thirteenth iteration.
Input Validation: Do not accept a value less than 1 for the number of floors. Do not accept a number less than 10 for the number of rooms on a floor.
Average Rainfall
Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. The program should first ask for the number of years. The outer loop will iterate once for each year. The inner loop will iterate 12 times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month.
After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period.
Input Validation: Do not accept a number less than 1 for the number of years. Do not accept negative numbers for the monthly rainfall.
Population
Write a program that will predict the size of a population of organisms. The program should ask the user for the starting number of organisms, their average daily population increase (as a percentage), and the number of days they will multiply. A loop should display the size of the population for each day.
Input Validation: Do not accept a number less than 2 for the starting size of the population. Do not accept a negative number for average daily population increase. Do not accept a number less than 1 for the number of days they will multiply.
Celsius to Fahrenheit Table
In Programming Challenge 12 of Chapter 3, you were asked to write a program that converts a Celsius temperature to Fahrenheit. Modify that program so that it uses a loop to display a table of the Celsius temperatures 0–20, and the Fahrenheit equivalents.
The Greatest and Least of These
Write a program with a loop that lets the user enter a series of integers. The user should enter -99 to signal the end of the series. After all the numbers have been entered, the program should display the largest and smallest numbers entered.
Student Line Up
A teacher has asked all her students to line up according to their first name. For example, in one class Amy will be at the front of the line, and Yolanda will be at the end. Write a program that prompts the user to enter the number of students in the class, then loops to read that many names. Once all the names have been read, it reports which student would be at the front of the line and which one would be at the end of the line. You may assume that no two students have the same name.
Input Validation: Do not accept a number less than 1 or greater than 25 for the number of students.
Payroll Report
Write a program that displays a weekly payroll report. A loop in the program should ask the user for the employee number, gross pay, state tax, federal tax, and FICA withholdings. The loop will terminate when 0 is entered for the employee number. After the data is entered, the program should display totals for gross pay, state tax, federal tax, FICA withholdings, and net pay.
Input Validation: Do not accept negative numbers for any of the items entered. Do not accept values for state, federal, or FICA withholdings that are greater than the gross pay. If the sum of state tax + federal tax + FICA withholdings for any employee is greater than gross pay, print an error message and ask the user to reenter the data for that employee.
Savings Account Balance
Write a program that calculates the balance of a savings account at the end of a period of time. It should ask the user for the annual interest rate, the starting balance, and the number of months that have passed since the account was established. A loop should then iterate once for every month, performing the following:
Ask the user for the amount deposited into the account during the month. (Do not accept negative numbers.) This amount should be added to the balance.
Ask the user for the amount withdrawn from the account during the month. (Do not accept negative numbers.) This amount should be subtracted from the balance.
Calculate the monthly interest. The monthly interest rate is the annual interest rate divided by 12. Multiply the monthly interest rate by the balance, and add the result to the balance.
After the last iteration, the program should display the ending balance, the total amount of deposits, the total amount of withdrawals, and the total interest earned.
Note:If a negative balance is calculated at any point, a message should be displayed indicating the account has been closed and the loop should terminate.
Sales Bar Chart
Write a program that asks the user to enter today’s sales for five stores. The program should then display a bar graph comparing each store’s sales. Create each bar in the bar graph by displaying a row of asterisks. Each asterisk should represent $100 of sales.
Here is an example of the program’s output:
Enter today's sales for store 1: 1000 Enter Enter today's sales for store 2: 1200 Enter Enter today's sales for store 3: 1800 Enter Enter today's sales for store 4: 800 Enter Enter today's sales for store 5: 1900 Enter SALES BAR CHART (Each * = $100) Store 1: ********** Store 2: ************ Store 3: ****************** Store 4: ******** Store 5: *******************Population Bar Chart
Write a program that produces a bar chart showing the population growth of Prairieville, a small town in the Midwest, at 20-year intervals during the past 100 years. The program should read in the population figures (rounded to the nearest 1,000 people) for 1900, 1920, 1940, 1960, 1980, and 2000 from a file. For each year, it should display the date and a bar consisting of one asterisk for each 1,000 people. The data can be found in the
People.txtfile.Here is an example of how the chart might begin:
PRAIRIEVILLE POPULATION GROWTH (each * represents 1,000 people) 1900 ** 1920 **** 1940 *****Budget Analysis
Write a program that asks the user to enter the amount that he or she has budgeted for a month. A loop should then prompt the user to enter each of his or her expenses for the month and keep a running total. When the loop finishes, the program should display the amount that the user is over or under budget.
Random Number Guessing Game
Write a program that generates a random number and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display “Too high, try again.” If the user’s guess is lower than the random number, the program should display “Too low, try again.” The program should use a loop that repeats until the user correctly guesses the random number.
Random Number Guessing Game Enhancement
Enhance the program that you wrote for Programming Challenge 20 so it keeps a count of the number of guesses the user makes. When the user correctly guesses the random number, the program should display the number of guesses.
Square Display
Write a program that asks the user for a positive integer no greater than 15. The program should then display a square on the screen using the character ‘X’. The number entered by the user will be the length of each side of the square. For example, if the user enters 5, the program should display the following:
XXXXX XXXXX XXXXX XXXXX XXXXXIf the user enters 8, the program should display the following:
XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXXPattern Displays
Write a program that uses a loop to display Pattern A below, followed by another loop that displays Pattern B.
Pattern A Pattern B + ++++++++++ ++ +++++++++ +++ ++++++++ ++++ +++++++ +++++ ++++++ ++++++ +++++ +++++++ ++++ ++++++++ +++ +++++++++ ++ ++++++++++ + Using Files—Numeric Processing
If you have downloaded this book’s source code from the Computer Science Portal, you will find a file named Random.txt in the Chapter 05 folder. (The Portal can be found at www.pearsonhighered.com/gaddis.) This file contains a long list of random numbers. Copy the file to your system, then write a program that opens the file, reads all the numbers from the file, and calculates the following:
The number of numbers in the file
The sum of all the numbers in the file (a running total)
The average of all the numbers in the file
The program should display the number of numbers found in the file, the sum of the numbers, and the average of the numbers.
Using Files—Student Line Up
Modify the Student Line Up program described in Programming Challenge 14 so it gets the names from a file. Names should be read in until there is no more data to read. If you have downloaded this book’s source code you will find a file named LineUp.txt in the Chapter 05 folder. You can use this file to test the program.
Personal Web Page Generator
Write a program that asks the user for his or her name, then asks the user to enter a sentence that describes himself or herself. Here is an example of the program’s screen:
Enter your name: Julie Taylor Enter Describe yourself: I am a computer science major, a member of the Jazz club, and I hope to work as a mobile app developer after I graduate.Once the user has entered the requested input, the program should create an HTML file, containing the input, for a simple webpage. Here is an example of the HTML content, using the sample input previously shown:
<html> <head> </head> <body> <center> <h1>Julie Taylor</h1> </center> <hr /> I am a computer science major, a member of the Jazz club, and I hope to work as a mobile app developer after I graduate. <hr /> </body> </html>Average Steps Taken
A Personal Fitness Tracker is a wearable device that tracks your physical activity, calories burned, heart rate, sleeping patterns, and so on. One common physical activity that most of these devices track is the number of steps you take each day.
If you have downloaded this book’s source code, you will find a file named steps.txt in the Chapter 05 folder. The steps.txt file contains the number of steps a person has taken each day for a year. There are 365 lines in the file, and each line contains the number of steps taken during a day. (The first line is the number of steps taken on January 1, the second line is the number of steps taken on January 2, and so forth.) Write a program that reads the file, then displays the average number of steps taken for each month. (The data is from a year that was not a leap year, so February has 28 days.)