Control structures to direct program flow Loops Control structures to direct program flow
Types of Loops do loop - executed statements at least once. After execution of the previous statements, evaluate a condition to determine if the loop should be repeated. do{ Statements; }while(condition);
do Loop int value; do{ System.out.print(“Enter an integer > 0”); value = in.nextInt(); } while(value>=0);
while loop While loops evaluate a condition before execution of subsequent statements. While loops are event driven. while(condition) { statements; }
Using a sentinel A sentinel serves as a signal for termination. int sentinel = -1; while(!=sentinel) { System.out.println(“hello”); }
For Loop are used for executing block statements a fixed number of times. The condition is checked before each iteration Initialization happens once before the loop starts for(int i = 0; i<100; i+=50) { initialization Condition update sum= sum + i; } The update happens after each loop iteration
For loop example: for(int i=0; i<=5 i=i+1) { S.O.P(i+”,”); } i at: Result Condition(i<=5) true 1 2 3 4 5 6 No longer loops false for(int i=0; i<=5 i=i+1) { S.O.P(i+”,”); } Result: 0,1,2,3,4,5