Chapter 5 Flashcards
Why is repetition needed?
Allows the use efficient use of variables. It can also input, add and subtract.
What is a while expression?
Statement that can be simple or compounded
What is compounded in terms of a loop?
Multiple statements surrounded by {}
What is the expression in a loop used for?
It acts as a decision maker and is usually a logical expression.
What is a counter control loop?
When you want to do something a certain amount of times.
int counter=0;
while(counter
What are some common mistakes for counter control loop?
Make sure that in the loop body that will eventually make the test condition.
Don’t put a semi-colon after the test condition.
What is Sentinel-controlled loop?
A sentinel or dummy value is tested for to determine if the loop should end. int sum=0; cout > num; while(num != -1) { num += num; cin >> num; }
What is a Flag-Controlled Loop?
if you are looking for something and can quit once you find it you can set the boolean value to false, once you found what you needed. bool done = false; while(!done) { Do something...; if(found what you wanted to) { done = true; } Do something else...; }
EOF-controlled loop?
If you are importing from a file, there is a function called eof() that returns true if you have reached
the end of the file, and false otherwise. Alternatively, the input stream variable itself will return true if
(1) you are not at end of the file and (2) you do not have an input error.
ifstream inFile; // declare the input stream variable
string word; // variable to hold input
inFile.open(“test.txt”); // open the file
while(inFile) // test the loop control variable
{
inFile»_space; word; // update the loop control variable
…
}
What is a do while loop?
Work just like a while loop, but are the body of the loop will be run at least once. Syntax: do { These things } while(guard statement);
What is a for loop?
This type of loop runs for a specific number of times.
Syntax:
for (initial statement; loop condition; update statement)
{
statement;
}
• The initial statement, loop condition, and update statement are called for loop control
statements
• It is like a counter controlled while loop, but you initialize, compare and update the counter all
on the first line.
If you know how many repetitions that are needed for the loop then use a….
For loop.
If you do not know how many repetitions that are needed for the loop then use the….
Do-while loop.
If you do not know how many repetitions that are needed for the loop and it might be zero then use the…
While loop.
What is the break statement used for?
To exit early from a loop and to skip the remainder of the switch structure.