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 love Java”); ▫ That wouldn’t be pretty Can we make that happen more easily?
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)
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 }
While Loop - Flow Chart Condition Some Code true false int i = 0; while(i < 125) { System.out.println(“I love Java”); i = i + 1; }
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
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
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
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
Let’s Trace int i = 0; while(i < 4) { System.out.println(“I love Java”); i = i + 1; } 4 i I love Java
Uh Oh.. What’s wrong? int i = 0; while(i < 4); { System.out.println(“I <3 Java”); i = i + 1; } Creates an infinite loop
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,