Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Computing Concepts Note Set 14. What if… You had to print “I love Java” to the screen 125 times. How? 125 lines of ▫ System.out.println(“I.

Similar presentations


Presentation on theme: "Introduction to Computing Concepts Note Set 14. What if… You had to print “I love Java” to the screen 125 times. How? 125 lines of ▫ System.out.println(“I."— Presentation transcript:

1 Introduction to Computing Concepts Note Set 14

2 What if… You had to print “I love Java” to the screen 125 times. How? 125 lines of ▫ System.out.println(“I love Java”); ▫ That wouldn’t be pretty Can we make that happen more easily?

3 2 Types of Loops Counter-Controlled Loops ▫ use a counter to determine how many times the loop body executes ▫ “Enter 10 numbers” ▫ “Print this that and the other 25 times” Sentinel Controlled ▫ Wait for a special value (sentinel value) to be entered ▫ “Enter a positive number” (anything negative is sentinel) ▫ “Enter -1 to quit” ( -1 is the sentinel value)

4 Repetition Executing a sequence of statements multiple times governed by a condition ▫ Loop will execute while condition is true. Three looping constructs in Java ▫ We’ll start with the while loop while(conditionIsTrue) //execute some logic while(conditionIsTrue) { //execute multiple //lines of logic }

5 While Loop - Flow Chart Condition Some Code true false int i = 0; while(i < 125) { System.out.println(“I love Java”); i = i + 1; }

6 Let’s Trace int i = 0; while(i < 4) { System.out.println(“I love Java”); i = i + 1; } 0 i I love Java I love Java

7 Let’s Trace int i = 0; while(i < 4) { System.out.println(“I love Java”); i = i + 1; } 1 i I love Java I love Java I love Java

8 Let’s Trace int i = 0; while(i < 4) { System.out.println(“I love Java”); i = i + 1; } 2 i I love Java I love Java I love Java I love Java

9 Let’s Trace int i = 0; while(i < 4) { System.out.println(“I love Java”); i = i + 1; } 3 i I love Java I love Java I love Java I love Java I love Java

10 Let’s Trace int i = 0; while(i < 4) { System.out.println(“I love Java”); i = i + 1; } 4 i I love Java

11 Uh Oh.. What’s wrong? int i = 0; while(i < 4); { System.out.println(“I <3 Java”); i = i + 1; } Creates an infinite loop

12 Infinite Loops Loops that start but never stop – stopping condition is wrong or missing int i = 0; while(i >= 0) { System.out.println(“I <3 Java”); i = i + 1; } This condition will never be false …never ever Usually want it to be true for a while,


Download ppt "Introduction to Computing Concepts Note Set 14. What if… You had to print “I love Java” to the screen 125 times. How? 125 lines of ▫ System.out.println(“I."

Similar presentations


Ads by Google