1 / 11

Loops in Java

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

Télécharger la présentation

Loops in Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Loops in Java “For” Loops And “While” Loops

  2. Why major in cs?Show me the numbers Source: msn.careebuilder.com

  3. 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!

  4. 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?

  5. 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

  6. 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

  7. For Loop Example 2: Count up by 5 • Here we increment the variable by 5 and count up to 50

  8. For Loop Example 3 • Here is a loop that counts down from 100 to 0.

  9. While Loops • The statements are executed while the expression is true • The expression can be any boolean expression

  10. 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

  11. While Loop Example 1 • In the example, the condition is I < 5 • The loop statement is executed while i is less than 5

More Related