Unit 4 - Iteration Flashcards
iteration statements
Change the flow of control by repeating a set of statements zero or more times until a condition is met
Loop
Repetition of statements
Repeating a series of steps over & over and over
Structure of while loop
while (/*Boolean expression/*) { //statement one; //statement two; // ... }
Loop control variable
//initialize LCV while (/* check LCV*/) { //statement one; //statement two; //.... //update loop control variable }
A loop is an infinite loop when
the Boolean expression always evaluate to true
If the Boolean expression evaluates to false initially,
the loop body is never executed at all
Algorithm to sum individual digits given a number
Using mod, integer division, and while loop to do so
1 - Given an integer called number
2 - Create a variable for the sum
3 - Use mod to isolate the last digit of the number
4 - add the last digit to sum
5 - use integer division to eliminate the last digit from the number
6 - Repeat while there are still digits
7 - display the sum
Algorithm to calculate the number of years it would take to reach your goal using Interest
1 - Given an integer called numYears
2 - Create a variable for the total
3 - Add total to total multiplied by 10 years
4 - increase year by one and print out yearly balance
5 - Repeat until total reaches 1000
6 - Display numYears
Algorithm to sum first 10 positive multiples of 4
1 - Given an integer called counter 2 - Create a variable for the sum 3 - Add sum to counter multiplied by 4 4- Increase counter by one 5 - Repeat until value reaches 10 6 - Display sum
for loop header
3 parts
initialization
Boolean expression
increment or decrement
in a for loop, initialization is
only executed once before the first Boolean expression evaluation
In each iteration of a for loop, the increment statement is executed after
the entire loop body is executed and before the Boolean expression is evaluated again
Structure of a for loop
for (initialization;Boolean expression; update)’
a for loop can be rewritten into an
equivalent while loop and vice versa
When statements need to repeat a defined number of time, which type is more appropriate?
for loop may be more appropriate as start and end values can be seen on one line