Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Fall 2008ACS-1903 Ch 4 Loops and Files while loop do-while loop Other topics later on …

Similar presentations


Presentation on theme: "1 Fall 2008ACS-1903 Ch 4 Loops and Files while loop do-while loop Other topics later on …"— Presentation transcript:

1 1 Fall 2008ACS-1903 Ch 4 Loops and Files while loop do-while loop Other topics later on …

2 2 Fall 2008ACS-1903 Incrementing and Decrementing Variables by 1 number = number + 1 ; number += 1; number = number - 1 ; number -= 1 ; number++; ++number; number --; --number;

3 3 Fall 2008ACS-1903 while loops while Pre-test (expression tested before the iteration) Loop could be executed zero times do-while Post-test (expression tested after the iteration) Loop executed at least once

4 4 Fall 2008ACS-1903 Flowchart for while Boolean Expression Loop statement(s) false true The statements comprising the loop body are executed while the expression is true. pre-test

5 5 Fall 2008ACS-1903 Reading keyboard input until a sentinel is reached studentNumber=keyboard.nextInt(); countStudents = 0; while (studentNumber != 0) { countStudents++; studentNumber=keyboard.nextInt(); } Sometimes systems are designed to process some data until a “special” value is encountered. ReadUntilSentinel.java

6 6 Fall 2008ACS-1903 Example studentNumber=keyboard.nextInt(); // get student numbers until the sentinel of 0 is encountered while (studentNumber != 0) { mark = keyboard.nextDouble(); if (mark < 50) grade = "F"; else if (mark < 60) grade = "D"; else if (mark < 65) grade = "C"; else if (mark < 70) grade = "C+"; else grade = "B"; // display the grade System.out.println(studentNumber+" "+mark+" "+grade); studentNumber=keyboard.nextInt(); } Read student numbers and marks -until sentinel of 0 for student number -if there is a student number, there will be a mark too -assign grades based on marks What is the flowchart for this? marksAndGrades.java

7 7 Fall 2008ACS-1903 Flowchart for do-while Boolean Expression Loop statement(s) false true The statements comprising the loop body are executed repeatedly until the expression becomes false. post-test

8 8 Fall 2008ACS-1903 Summing the digits of a number int number = 373 ; do { sum +=(number % 10); number=number/10; } while (number!=0); Sometimes a process can be used that can or must execute at least once and so it can be structured with a loop with a post-test. SumDigitsOfInteger.java


Download ppt "1 Fall 2008ACS-1903 Ch 4 Loops and Files while loop do-while loop Other topics later on …"

Similar presentations


Ads by Google