(You must still copy notes by hand into notebook!)
Loops
– Allow code to be repeated a number of times (called iterations).
FOR
loops – Loop as long as a condition is true.
FOR loops have a control variable which will be part of the condition….this variable is initialized at the start of the loop.
3 PARAMETERS
Initialize control
variable
for (j = 0; j < 10; j++) Change variable value.
{
//looping code here; Condition
that causes
} structure
to loop when
true
Will
start j at 0, add one each time, and loop as long as j < 10
for
(k = 10; k > 0; k--)
{
//code;
}
for
(m = 5; m < 100; m = m + 5)
{
//code;
}
for
(j = 0; j != 10; j++)
{
//code;
}
for
(t = a; t > b; t++)
{
//code;
}
Similar to for loops, but are typically triggered to stop by something that happens inside the loop.
· User answers “No” or “Yes”
to a question
· Key condition is met…etc
While
loops – keyword is while, followed by condition
Condition
must be true in order for loop to begin and loop will continue as long as
condition stays true.
Examples:
while
(x != 3)
{
//code;
};
Note: condition must be true to start loop – useful when you’re not sure whether you would want to use the code or not.
Do/While
Loops: keyword is DO, followed by code, followed by
while with condition. Condition must be
true in order to repeat code.
do
{
//code;
}
while (
x != 3);
Summary:
· Use a FOR loop
when you know how many times you will loop (or when the program determines
this.)
· Use a DO / WHILE
loop when you want to loop at least once, and the trigger to stop the loop is
inside the loop.
· Use a WHILE loop
when you might not ever want to loop, but if you do, the trigger to stop the
loop is inside the loop