Presentation is loading. Please wait.

Presentation is loading. Please wait.

Loops –For For Reading for this Lecture, L&L, Part of 5.8.

Similar presentations


Presentation on theme: "Loops –For For Reading for this Lecture, L&L, Part of 5.8."— Presentation transcript:

1 Loops –For For Reading for this Lecture, L&L, Part of 5.8

2 The for Statement A for statement has the following syntax: for ( initialization ; condition ; increment ) statement; The initialization is executed once before the loop begins The statement is executed until the condition becomes false The increment portion is executed at the end of each iteration

3 The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; }

4 The for Statement An example of a for loop: The initialization section can be used to declare a variable Like a while loop, the condition of a for loop is tested prior to executing the loop Therefore, the body of a for loop will execute zero or more times for (int count=1; count <= 5; count++) System.out.println (count);

5 The for Statement The increment section can perform any calculation A for loop is well suited for executing the body a specific number of times that can be calculated or determined in advance See Multiples.java (page 248)Multiples.java See Stars.java (page 250)Stars.java for (int num=100; num > 0; num -= 5) System.out.println (num);

6 The for Statement Each expression in a for statement is optional If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation is performed “Forever” can be written as: for (;;) {body;}

7 The for Statement public class ForDemo { //Execution always starts from main public static void main(String[] args) { System.out.println(“Enter a number:”); Scanner keyboard = new Scanner(System.in) int num = keyboard.nextInt(); for(int count = 1; count <= num; count++) { System.out.println(count); }

8 The for Statement for( Initialization_Action ; Boolean_Expression ; Update_Action) Loop_Body The loop body may be either a single statement or more likely a compound statement

9 The for Statement for( Initialization_Action ; Boolean_Expression ; Update_Action) Loop_Body true Start Execute Initialization_Action false End loop Evaluate Boolean_Expression Execute Loop_Body Execute Update_Action

10 The for Statement for( int count = 1 ; count <= num ; count++) { System.out.print(count + “,”); } true Start Execute int count = 1 false End loop Evaluate count <= num Execute { System.out.print(count + “,”); } Execute count++


Download ppt "Loops –For For Reading for this Lecture, L&L, Part of 5.8."

Similar presentations


Ads by Google