1 / 30

Control Statements

Control Statements. Loops. Types of Control Structures. Why is Repetition Needed?. There are many situations in which the same statements need to be executed several times. Example: Formulas used to find average grades for students in a class. Loop

Download Presentation

Control Statements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Control Statements Loops

  2. Types of Control Structures

  3. Why is Repetition Needed? • There are many situations in which the same statements need to be executed several times. • Example: • Formulas used to find average grades for students in a class. • Loop Group of instructions that a computer executes repeatedly while some condition remains true

  4. Repetition • Java has three repetition, or looping, structures that let you repeat statements over and over again until certain conditions are met: • while • for • do…while

  5. counter-controlled loop • The loop shown below in pseudo code is called a counter-controlled while loop because its repetition is managed by a loop control variable whose value represents a count. Set loop control variable to an initial value While loop control variable < final value ... //Do something multiple times Increase loop control variable by 1 (or step size).

  6. Syntax: while (expression) statement Statements must change value of expression to false. A loop that continues to execute endlessly is called an infinite loop (expression is always true). The while Looping (Repetition) Structure

  7. Example 1This slide shows a program fragment that computes and displays the gross pay for seven employees. The loop body is the compound statements (those between { and }) count_emp = 1; while (count_emp <= 7) count_emp = 0; while (count_emp < 7) { System.out.print("Hours:“); hours = input.nextInt(); System.out.print("Rate:“); rate = input.nextInt(); pay = hours * rate; System.out.print(“Pay is:”+ pay); count_emp = count_emp + 1; //or count_emp++; } System.out.print("\n All employees processed\n“);

  8. Syntax of the while Statement: • Initialization. i.e. count_emp = 0; • Testing(condition). i.e. count_emp < 7 • Updating i.e. count_emp = count_emp + 1; • The above steps must be followed for every while loop. • If updating is skipped, it produce an infinite loop

  9. Example 2: Computing Sum • If we want to compute , we need to do 1+2+3+...+100 int sum =0, i = 1; while (i <= 100) { sum = sum + i; //or sum+=i; i = i + 1; //or i++; ++i; i+=1; } System.out.print(“Sum is :“+sum );

  10. The for Looping (Repetition) Structure • Specialized form of while loop. • Its primary purpose is to simplify the writing of counter-controlled loops. For this reason, the forloop is typically called a counted or indexed for loop. . • Syntax: for (initial statement; loop condition; update statement) statement Rewrite the previous examples using for loop

  11. The for Looping (Repetition) Structure • The following for loop outputs the word Hello and a star (on separate lines) five times: for (i = 1; i <= 5; i++) { System.out.println("Hello"); System.out.println("*"); } 2. The following for loop outputs the word Hello five times and the star only once: for (i = 1; i <= 5; i++) System.out.println("Hello"); System.out.println("*");

  12. The for Looping (Repetition) Structure • Does not execute if loop condition is initially false. • Update expression changes value of loop control variable, eventually making it false. • If loop condition is always true, result is an infinite loop. • Infinite loop can be specified by omitting all three control statements.

  13. Conditional Loops • In many programming situations, we will not be able to determine the exact number of loop repetitions before loop execution begins. • Sentinel-Controlled loops • Flag-Controlled loop

  14. Sentinel-Controlled while Loop • Used when exact number of entry pieces is unknown, but last entry (special/sentinel value) is known. • General form: Input the first data item into variable; while (variable != sentinel) { . . input a data item into variable; . . }

  15. Example :Program to compute the product of entered numbers import java.util.*;publicclass SentinelControlledWhileLoop{static Scanner console = new Scanner(System.in);staticfinalint SENTINEL = -999;publicstaticvoid main (String[] args){int number, prod= 0; SSystem.out.println("Enter positive integers ending with " + SENTINEL); number = console.nextInt();// Initialization while (number != SENTINEL) //testing { prod= prod * number; System.out.println("Enter positive integers ending with " + SENTINEL); number = console.nextInt(); //updating } System.out.println(“the product is “ + prod);}} Read input before loop

  16. Flag-Controlled while Loop • Boolean value used to control loop. • General form: boolean found = false; while (!found) { . . if (expression) found = true; . . . }

  17. bool found = false; int num =0;   while(!found) {         num++;         if (num == 3) { found = true; System.out.println("value of flag is:“ +found ); }          } }

  18. The do…while Loop (Repetition) Structure • Syntax: do statement while (expression); • Statements are executed first and then expression is evaluated. • Statements are executed at least once and then continued if expression is true.

  19. do…while Loop (Post-Test Loop)

  20. do…while Loop (Post-Test Loop) Example : i = 0 ; do { System.out.print(i + “ “ ) ; i = i + 5 ; }while ( i <= 30 ) ; output : 0 5 10 15 20 25 30

  21. break Statements • Used to • exit early from a loop. (while, for, and do...while) • skip remainder of switch structure. • Can be placed within if statement of a loop. • If condition is met, loop is exited immediately. • After the break statement executes, the program continues to execute with the first statement after the structure

  22. break Statements Example : int count ; for ( count = 1 ; count <= 10 ; count ++ ) { if ( count == 5) break ; System.out.print(count + “ ” ); } Output 1 2 3 4

  23. continue Statements • Used in while, for, and do...while structures. • When executed in a loop, the remaining statements in the loop are skipped; proceeds with the next iteration of the loop. • When executed in a while/do…while structure, expression is evaluated immediately after continue statement. • In a for structure, the update statement is executed after the continue statement; the loop condition then executes.

  24. continue Statements Example : int count ; for ( count = 1; count <= 10 ; count ++ ) { if ( count == 5) continue; System.out.print(count + “ ” )}; } Output 1 2 3 4 6 7 8 9 10

  25. Nested Control Structures • Provides new power, subtlety, and complexity. • if, if…else, and switch structures can be placed within while loops. • for loops can be found within other for loops. • Nested loops consist of an outer loop with one or more inner loops. • Each time the outer loop is repeated, the inner loops are reentered • Their loop control expressions are reevaluated • All required iterations are performed again

  26. Example: Sum of Scores of 3 sectionscalculate the total scores in each section for 3 sections. • Each section's scores are terminated by the sentinel -99.

  27. int sec, score, sum; System.out.print ("sum of scores for each section\n“); for (sec= 1 ; sec <= 3 ; ++sec) { sum = 0; for (score=input.nextInt(); score != -99; score=input.nextInt()) {sum += score; } System.out.print("Section: " +sec+ " sum of scores :” +sum); }

  28. Nested Control Structures for (inti = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) System.out.print("*"); System.out.println(); } Output: * ** *** **** *****

  29. Self read

More Related