Algorithms and Problem Solving Ch. 6: Control Structures
When Do You Use a For Loop? (2)
-for counting loops -use in any expression for printing, calling, and often methods -when you want to iterate through an object
While Structure:
N = 50; // Initializer while (N != 1) // Loop Entry Cond. (While N not 1) { System.out.print(N + " "); // Print N if (N % 2 == 0) // If N is even N = N / 2; // updater: (divide it by 2) else // If N is odd N = 3 * N + 1; // (updater) multiply N by 3 and add 1 } System.out.println(N); // Print N
When is the Do-While Loop Used? (2)
The do-while loop is designed for solving problems in which at least one iteration must occur. -do while loop in Java is similar to while loop except that the condition is checked after the statements are executed, *so do while loop guarantees the loop execution at least once.*
The Do-While Loop is known as a : _____ .Why? (2)
a post-test loop because do while loops check the condition after the block is executed, the control structure is often also known as a post-test loop
When Do you Use the While Loops?
for repetition until a certain condition is met
For Loop Syntax:
int i = 0; for ( int i = 0; i<= 9, i++) { body } for (initializer = starting value; loop bound; updater a.k.a inc or dec)
What are Pretest Loops? What are Some Examples? (2)
pretest loops tests the loop condition before executing the loop's body. ... The loop terminates as soon as the condition becomes false, and the control goes to the statement after the loop's body. ex: *while loops* and *for loops* are examples of pretest loops.
Switch Structure:
switch ( integralExpression ) { case integralValue2 : statement1; break; case integralValue2 : statement2; break; ... case integrealValueN : statementN; break; default: statementDefault; }