Sometimes algorithms have the need to repeat some actions
Iteration is the same as repetition
C++ many different iteration statements.
while ( condition ) statement ;
Wherever a statement is required you can use a single
statement or a compound statement using
{
statement1;
statement2;
statement3;
}
while statements require
INITIALIZATION OF THE LOOP VARIABLES
SET UP THE CONDITION
MAKE SURE THE CONDITION WILL EVENTUALLY BECOME FALSE
Simple loop to compute the sum of numbers:
int i, sum;
i = 1;
sum = 0;
while (i <= 10)
{
sum = sum + i;
i = i + 1;
}
example9.cpp and example9a.cpp
Common LOGIC error with loops are the following:
1. Forgetting the initialization 2. Not setting up the condition 3. Forgetting the increment
READING INPUT FROM A FILE
C++ provides the notion of a stream to make this convenient
Once you create a stream, you can use the same insertion and
extraction operators as you used with with cout and cin:
<< is used for output from an output stream
>> is used for input from an input stream
#include <iostream.h>
#include <fstream.h>
// input file stream is associated with an external file
ifstream inputfile("myinput.txt");
if (inputfile == NULL)
cout << "File does not exist!" << endl;
else
{
int sum = 0, i;
while ( (inputfile >> i) != NULL )
sum = sum + i;
cout << "Sum of numbers is: " << sum ;
}
Example reading inputs: example10.cppWRITING OUTPUT TO A FILE
ofstream outputfile("myoutput");
outputfile << "Put this line in the output file" << endl;
outputfile << i << j << k << endl;
Example of Input / Output from Files (example11.cpp)