Chapter 4 Flashcards
Explain the While Loop
Format:
while (condition)
{
statement A; // runs while the condition is true until condition is no longer true (called an iteration)
}
statement B; // the statement that is run once the condition is false
Explain the Do-While Loop.
Format:
do
{
statements;
}
while (condition);
Unlike while loops, do-while loops check the condition at the end and decide whether or not to repeat the loop.
Explain the For Loop
Format:
for (initialization; condition; update;)
{
statements;
}
Executes the initialization, loops through the code as long as the condition is true, and performs the update after each loop
For loops are great for when you want your loop to repeat a set amount of times.
What is a local variable?
A local variable is any variable declared inside of a loop. They only exist inside of that loop and cannot be accessed outside of the loop.
What is a global variable?
A global variable are variables that can be accessed anywhere in the entire program.
When should you use a while loop?
You should use a while loop when you know your loop isn’t going to run a fixed number of times or if the stopping condition is more complicated than a simple comparison.
Note: loops are interchangeable to accomplish the same purpose, however some loops are easier to use.
When should you use a do-while loop?
You should use a do-while loop when your loop needs to run at least once.
When should you use a for loop?
You should use a for loop when you know ahead of time that your loop will run a fixed number of times
In a for loop, what is the difference between i = 0 vs i = 1?
i = 0 means it starts at 0, while i = 1 means it starts at 1. This will affect your output which is why sometimes people may run into an off by one error.
What is a nested loop?
A nested loop is one loop inside of another.
Ex:
int i = 1, j;
while (i <= 3)
{
j = 1;
while (j <= i)
{
cout «_space;i «_space;”,” «_space;j «_space;“ - ”;
j++; }
i++;
cout «_space;endl;
}
*An example of what a nested loop may be used for is creating rows and columns (i = the row, j = column)
What is the purpose of a break statement?
A break statement is used to break out of the loop
Note: a break statement cannot be used to break out of multiple nested loops. It only jumps out of the inner loop.
What is the purpose of the continue statement?
A continue statement is used to skip the remaining part of the loop and continues to the next iteration.
What is the <random> library used for in C++ ?</random>
The <random> library in C++ allows us to use a random number generator</random>
What is rand() and what is its function?
- rand() is used to generate random integers
- it generates a random integer between 0 and RAND_MAX
What library do you need to include to use RAND_MAX?
include <cstdlib></cstdlib>