Repetition
- Algorithms
- Uses : Counting and Sentinel controlled
- Pseudocode
Increment/Decrement revisited
WHILE Loops
- Syntax
while (condition)
{
statements_in_the_loop;
}
- Semantics
- Evaluate the condition
- If the condition is true
Execute the statements in the loop
Jump back to the top of the loop (step 1.)
- Otherwise
Execute statements after the loop
- EXAMPLES, Examples, examples
int sum = 0, i = 1;
while (i < 10)
{
sum = sum + i;
i++;
}
TRY IT!
- Write a program that sums the numbers the user enters until
a negative number is entered
- Write a program that calculates the average of three exam scores. If
an exam score is below 0, keep asking for a correct number
DO-WHILE Loops
- Syntax
do
{
statements_in_the_loop;
}
while (condition);
- Note the semicolon after the "(condition)"
- Semantics
- Execute the statements in the loop
- Evaluate the condition
- If the condition is true
Jump back to the top of the loop (step 1.)
- Otherwise
Execute statements after the loop
TRY IT!
Write a program that displays a menu of options until the user
enters the character to end:
- sum two numbers
- subtract two numbers
- multiple two numbers
- Quit
FOR loop & Counter Controlled loops
- Syntax for initial, final, and modifier
for (initialize_lcv; condition; modify_lcv)
{
statements_in_loop;
}
statements_after_loop
- Semantics
- Initialize lcv
- Evaluate the condition
- If the condition is true
Execute the statements in the loop
Jump back to the top of the loop (step 1.)
- Otherwise
Execute statements after the loop
- EXAMPLES
for (I=0; I<9; I++)
cout << I;
TRY IT!
- Write a program that sums the numbers from 1 until the number the
user enters
- Write a program that displays the characters for the ASCII codes from
0 to 127
- Using loops to track a total
- Sentinel controlled loops
- Array preview
- Deciding which loop to use
Break
- Used to exit loop
- Caution when using
- Not "structured"
- Sometimes appropriate
Continue
- Used to skip to next iteration of loop
- Caution when using
- Not "structured"
- Rarely appropriate
Combining Control structures
- Programming using nested structures.
Files - Just FYI. This is covered in CPSC 246
- Another way to get input into the program
- Pre-formatted text file
- Data not entered from keyboard
- Need to learn how to:
- Declare the file variable
- Open the filed and connect it to the actual file on disk
- Input (i.e., read) from a file
- Output to a file
- Close the file when you are done
- Need to include fstream
- #include <fstream>
- Declare an input file
- ifstream myFile;
- Declare an output file
- ofstream myReport;
- Open a file:
- myFile.open("theInput.txt");
- myReport.open("results.txt");
- Close a file
- myFile.close();
- myReport.close();
- Writing to a file uses the filename instead of cout
- myReport << "Report Title\n";
- myReport << "by Deborah Whitfield \n";
- Reading from a file uses the filename instead of cin
- myFile >> myNumericVariable;
- myFile >> myStringVariable;