90 likes | 304 Views
Loop . 10/22/2012. Outline. Loop 1: for Loop 2: while Loop 3: do while Practice. f or loop (1/2). for (expression) { statement_1; statement_2 ; } If the statement body only has one statement, the left brace “{” and right brace “}” are often dropped for ( expression) statement.
E N D
Loop 10/22/2012
Outline • Loop 1: for • Loop 2: while • Loop 3: do while • Practice
for loop (1/2) • for (expression) { statement_1; statement_2; } • If the statement body only has one statement, the left brace “{” and right brace “}” are often dropped • for (expression) statement Control variable Initialization Condition Increment Result: Example:
for loop (2/2) • A possible mistake • The Increment is forgotten Example: Result:
while loop (1/2) • while (expression) { statement_1; statement_2; } • If the statement body only has onestatement, the left brace “{” and right brace “}” are often dropped • while (expression) statement; Example: Result:
while loop (2/2) • 2 possible mistake: • The left and right brace are forgotten • while (expression); Example: Result: Example: Result:
do while loop • do { statement_1; statement_2; } while (expression); • If the statement body only has one statement, the left brace “{” and right brace “}” are often dropped • while (expression) statement; • The semicolon “;” at the end of while cannot be omitted Example: Result:
Practice Time • Greatest Common Divisor (GCD) • GCD of two or more non-zero integers, is the largest positive integer that divides the numbers without a remainder • For example, the GCD of 8 and 12 is 4 • Sample input • Sample output • Hint • Euclidean algorithm Example: 2 12 1 8 4 8 0 4