Terminology
⟹ Flow of Control = which statement gets executed next? A.k.a., logic flow.
⟹ Control Structures = statements which control logic flow
⟹ Three Categories of Control Structures:
- Sequence (from the top to the bottom, in order)
- Selection (if statement)
- Iteration (while, for, and do-while loops)
Examples
- Meet the Loops (modern javascript tutorial)
- Flip a coin. Rewrite using a do-while loop.
Optional Loop Practice
The peasant multiplication algorithm (PMA) is an ancient system for multiplying two numbers. It requires only the ability to double, divide by 2, and add.
Exercise: Translate this pseudocode Peasant Multiplication Algorithm (PMA) into a JavaScript function named pma that accepts two numbers and returns their product.
//pseudocode notation-- this is not JavaScript
Begin PMA
var i = 7, j = 10, prod = 0;
while(i not equal 0)
if(i is odd)
answer = answer + j
divide i by 2, and discard remainder
double j
display i, j, answer
End PMA.