 Download Download Presentation Loops

# Loops

Download Presentation ## Loops

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. Loops This slide set was compiled from the Absolute Java textbook slides (Walter Savitch) and the professor’s own class materials. CSS161: Fundamentals of Computing

2. Loops • Loop: • Loop body, (i.e., Statements) to be repeated • A Boolean expression to terminate the repetition • Iteration: • Each repetition of the loop body • Three types of loop statements • while loop: a Boolean expression evaluated at top of each iteration • do-while loop: a Boolean expression evaluated at bottom of each iteration • for loop: is similar to while loop but additionally includes initialization statements and post-iteration updating statements CSS161: Fundamentals of Computing

3. while Statement • Syntax while (Boolean_Expression) Statement Or while (Boolean_Expression) { Statement_1 Statement_2 Statement_Last } • Example int countDown = 3; while ( countDown > 0 ) { System.out.println( “Hello” ); countDown = countDown - 1; } Boolean Expression? false true Statement(s) CSS161: Fundamentals of Computing

4. do-while Statement • Syntax do Statement while (Boolean_Expression); Or do { Statement_1 Statement_2 Statement_Last } while (Boolean_Expression); • Example countDown = 3; do { System.out.println( “Hello” ); countDown = countDown – 1; } while ( countDown > 0 ); Statement(s) true Boolean Expression? false CSS161: Fundamentals of Computing

5. Algorithms and Pseudocode • Algorithm: a set of precise instructions that leads a solution. • Example: Sorting Algorithms (Selection, Bubble, Insertion, Quick, Merge) • Sorting three integers: • Declare three variables: a, b, and c; • Read keyboard inputs into a, b, and c; • Swap a and b if a < b • Swap a and c if a < c • Swap b and c if b < c • Print out a, b, and c • Pseudocode: a mixture of a programming language and human language to write an algorithm • Sorting three integers: • int a, b, c, tmp; • // read keyboard inputs into a, b, and c; • if ( a < b ) { • tmp = a; • a = b; • b = tmp; • } • if ( a < c ) { • tmp = a; • a = c; • c = tmp; • } • if ( b < c ) { • tmp = b; • b = c; • c = tmp; • } • // print out a, b, and c CSS161: Fundamentals of Computing

6. Sentinel Value Pseudocode to Program import java.util.Scannaer; public class Averager { public static void main( String[] args ) { Scanner keyboard = new Scanner( System.in ); System.out.println( “Enter nonnegative scores.” ); System.out.println( “End with a negative number.” ); System.out.println( “I will compute their average” ); double next, sum = 0; int count = 0; next = keyboard.nextDouble( ); while( next >= 0 ) { sum += next; count++; next = keyboard.nextDouble( ); } if ( count == 0 ) System.out.println( “No scores entered.” ); else { double average = sum/count; System.out.println( count + “ scores read” ); System.out.println( “The average is ” + average ); } } } Give the user instructions. count = 0; sum = 0; Read a number and store it in a variable named text. While ( next >= 0 ) { sum = sum + next; count++; Read a number and store it in next. } The average is sum/count provided count is not zero. Output the results CSS161: Fundamentals of Computing

7. Self-Test Exercises • Work on Textbook p131’s exercises 22 ~ 27. CSS161: Fundamentals of Computing

8. for Statement • Syntax for (Initialization; Boolean_Expression; Updates) Body • Examples int next, sum = 0; for ( next = 0; next <= 10; next++ ) { sum = sum + next; System.out.println( “sum up to ” + next + “ is ” + sum ); } Scanner keyboard = new Scanner( System.in ); int value = keyboard.nextInt( ); int limit = keyboard.nextInt( ); for ( int mult = value; mult <= limit; mult += value ) System.out.println( mult ); Initialization false Boolean Expression? true Statement(s) Updates CSS161: Fundamentals of Computing

9. for-Equivalent while Loop Syntax CSS161: Fundamentals of Computing

10. Comma in for Statements • Multiple initializing actions, each separated by a comma • Multiple updating actions, each separated by a comma • Syntax: for ( Init1, Init2, ..; Boolean_Expression; update1, update2, … ) body • Notes: • If Initialization also declares variables (valid only within the for-loop), all declared variables must be the same type. • Updates can replace body that can be even eliminated. (the last semicolon is necessary.) • Example: for ( term = 1; sum = 0; term <= 10; sum += term, term++ ) ; // empty body CSS161: Fundamentals of Computing

11. Examples • Syntactically illegal for ( int term = 1, double sum = 0; term <= 10; term++ ) sum = sum + term; double sum; for ( int term = 1, sum = 0; term <=10; term++ ) sum = sum + term; • Syntactically legal for ( int term = 1; sum = 0; term <= 10; term++ ) sum = sum + term; Should be int CSS161: Fundamentals of Computing

12. Repeat N Times Loops • Print N times (1-indexed counting) public static final int N = 30; for ( int count = 1; count <= N; count++ ) System.out.println( “Hop, Step, Jump” ); • Alternative way to count (0-indexed counting) for ( int count = 0; count < N; count++ ) System.out.println( “Hop, Stem, Jump” ); int[] array = new int[N]; for ( int index = 0; index < N; index++ ) array[index] = 100; CSS161: Fundamentals of Computing

13. Empty Statement in a for Loop • Pitfall for ( int count = 0; count <= 10; count++ ); System.out.println( “count = ” + count ); • Correct for ( int count = 0; count <= 10; count++ ) System.out.println( “count = ” + count ); • Intentional for ( int count = 0; count <= 10; System.out.println( “count = “ + (count++ ) ); An empty statement: meaninglessly repeated 10 times; CSS161: Fundamentals of Computing

14. number <= 12 count++ if ( Boolean_expression ) break; Infinite Loops • The Boolean expression in a do-while/while/for loop must eventually end up with “false”. • Otherwise the loop can’t get finished. • Examples number = 1; while ( number != 12 ) { System.out.println( number ); number = number + 2; } for ( int count = 0, limit = 5; count < limit; limit++ ) System.out.println( count ); for( ; ; ) { } while ( true ) { } CSS161: Fundamentals of Computing

15. Nested Loops • When nested, the inner loop iterates from beginning to end for each single iteration of the outer loop • Examples • What results will be printed out? int rowNum, columnNum; for (rowNum = 1; rowNum <=3; rowNum++) { for (columnNum = 1; columnNum <=2; columnNum++) System.out.print(" row " + rowNum + " column " + columnNum); System.out.println(); } • What results will be printed out? for ( int row = 1; row <= 10; row++ ) { for ( int star = 1; start <= row; star++ ) System.out.print( “*” ); System.out.println( ); } CSS161: Fundamentals of Computing

16. break Statement • Breaking out of the current loop for ( int x = 0; x < MAX; x++ ) if ( ( next = keyboard.nextInt( ) ) <= 0 ) break; for ( int x = 0; x < MAX; x++ ) for ( int y = 0; y < MAX; y++ ) for ( int z = 0; z < MAX; z++ ) if ( ( next = keyboard.nextInt( ) ) <= 0 ) break; • Breaking out of the current and outer loops all under a give label outerLoop: for ( int x = 0; x < MAX; x++ ) middleLoop: for ( int y = 0; y < MAX; y++ ) innerLoop: for ( int z = 0; z < MAX; z++ ) { if ( ( next = keyboard.nextInt( ) ) < 0 ) break innerLoop; if ( next == 0 ) break middleLoop; if ( next < 100 ) break outerLoop; } } } CSS161: Fundamentals of Computing

17. continue Statement • Ends the current iteration of the nearest enclosing loop, and then • Starts the next iteration. for ( int num = 0; num < MAX; num++ ) { if ( ( div = keyboard.nextInt( ) ) == 0 ) continue; System.out.println( num + “/” + div + “=“ + num/div ) } for ( int x = 0; x < MAX; x++ ) for ( int y = 0; y < MAX; y++ ) for ( int z = 0; z < MAX; z++ ) { if ( ( div = keyboard.nextInt( ) ) <= 0 ) continue; System.out.println( ( x + y + z ) / div ) } CSS161: Fundamentals of Computing

18. exit Statement • break ends a loop, but does not end the program. • System.exit(0) immediately ends the program. • 0 used to indicate a normal ending of the program. System.out.println( “Enter a negative number:” ); int negNumber = Kyeboard.nextInt( ); if ( negNumber >= 0 ) { System.out.println( negNumber + “>= 0 ... Program aborting.” ); System.exit( 0 ); } CSS161: Fundamentals of Computing

19. Self-Test Exercises • Work on Textbook P140’s exercises 28 ~ 39 CSS161: Fundamentals of Computing