Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS2011 Introduction to Programming I Loop Statements (I)

Similar presentations


Presentation on theme: "CS2011 Introduction to Programming I Loop Statements (I)"— Presentation transcript:

1 CS2011 Introduction to Programming I Loop Statements (I)
Chengyu Sun California State University, Los Angeles

2 Certain Things Can Be Done by Both Human and Computer
For example, in our labs we have done: convert mile to kilometer, sort three numbers, calculate the decimal value of a 4-digit binary number …

3 Certain Things Are More Suitable for Computers
Display "Welcome to Java" a thousand times Sort one million numbers … … Loop statements allow us to make computers do what they do best: repetitive work at very high speed

4 Example: Welcome20 Display "Welcome to Java" 20 times

5 while statement while ( boolean-expression ) { statement(s) }
If the boolean expression evaluates to true, execute the statement(s) in {}; repeat until the condition is no longer true {} can be omitted if there's only one statement

6 Flow of while Statement
while(condition) false true statement(s)

7 if vs. while if(condition) false while(condition) false true true
statements statements

8 Key Things for a Loop Statement
Initial state Loop condition Change of state inside the loop that affects the loop condition Iteration counter Must-have Often used

9 Avoid Common Problems When Using Loop Statements
Make sure the loop condition eventually become false to avoid infinite loop Specify the loop condition carefully to avoid off-by-one error E.g. should it be count < 20 or count <= 20 in the Welcome20 example?

10 Example: Bin2Dec Calculate the decimal value of a given binary number
For example: 1101 = 1 x x x x 23 = 1 x x x x 8 = = 13

11 Construct the Loop Find the repeating pattern and decide the unit of work done in each iteration Initial state ?? Change of state ?? Loop condition ??

12 Example: Addition Quiz Revisited
The program asks if the user wants to continue after each question "Y" or "y" : create another question "N" or "n": exit

13 do … while statement do { statement(s) } while ( boolean-expression );
It's like a while loop except that the statement(s) will be executed at least once Notice the ; at the end Flow chart ?? AdditionQuiz is more natural with do…while


Download ppt "CS2011 Introduction to Programming I Loop Statements (I)"

Similar presentations


Ads by Google