230 likes | 674 Views
Loops in Java. “ For ” Loops And “ While ” Loops. Why major in cs? Show me the numbers. Source: msn.careebuilder.com. Before we begin: Always write comments. In processing/Java use // to indicate a comment E.g. // THIS IS A COMMENT
E N D
Loops in Java “For” Loops And “While” Loops
Why major in cs?Show me the numbers Source: msn.careebuilder.com
Before we begin:Always write comments • In processing/Java use // to indicate a comment • E.g. • // THIS IS A COMMENT • I am taking off 5-10 points on assignments for the rest of the semester for missing comments!
Why use a loop? • These two sections of code do the same thing • The first has 22 lines • The second uses a loop and has 6 lines • Which is better?
For loop syntax • Initialiaztion - assign a variable a starting value • Exit condition - test the variable and determine when to end the loop • Incrementor - how much to change the variable each time through the loop
Example 1: Using a for loop • The loop counts from 0 to 4 (or keeps going while I is less than 5) • The bottom picture is the output from the loop
For Loop Example 2: Count up by 5 • Here we increment the variable by 5 and count up to 50
For Loop Example 3 • Here is a loop that counts down from 100 to 0.
While Loops • The statements are executed while the expression is true • The expression can be any boolean expression
Less than or equal to <= 4 <= 5 is true Greater than or equal to >= 4 >= 4 is true Not equal != 4 != 4 is false 5 != 5 is true Less than < 5 < 7 is true 7 < 4 is false Greater Than 5 > 3 is true 4 > 9 is false Exactly equal == 4 == 4 is true 6 == 5 is false Relational Operations
While Loop Example 1 • In the example, the condition is I < 5 • The loop statement is executed while i is less than 5