1 / 10

Introduction to While and For Loops in Java

Learn about while and for loops in Java, including their syntax, usage, and common pitfalls to avoid. This topic covers the basics of loop repetition and how to control the number of iterations.

chandrat
Download Presentation

Introduction to While and For 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. Week 8 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham

  2. Week 8 Topics 8.1.1 while Loops 8.1.2 for Loops

  3. 8.1.1 while Loops • It is often useful to be able to repeatedly execute one or more statements • A loop refers to such a repetition • A while loop statement executes a block of code repeatedly. A condition controls how often the loop is executed.

  4. 8.1.1 while Loops cont. • The while loop statement construct is while (condition) statement; • Use brackets if there are multiple statements in the body of the while loop statement • while (balance < targetBalance) { years++; double interest = balance * rate / 100; balance = balance + interest; }

  5. 8.1.1 while Loops cont. False balance < targetBalance ? True Increment years Add interest to balance

  6. 8.1.1 while Loops cont. • The do/while loop can be used if the loop should always be executed at least one time • The do/while loop statement construct is do statement; while (condition) double value; do { System.out.print(“Enter a positive number: ”; value = in.nextDouble(); } while(value <= 0);

  7. 8.1.2 for Loops • The for loop is useful when the number of iterations are known • The for loop statement construct is for (initialization; condition; update) statement; • for (i = 1; i <= years; i++) { double interest = balance * rate / 100; balance = balance + interest; }

  8. 8.1.2 for Loops cont. i = 1 initialization False condition i <= years? True Add interest to balance update i++

  9. 8.1.1 and 8.1.2 Loops cont. • Review the textbook (sections 7.1 and 7.2) to learn to avoid these loop coding pitfalls: • Infinite loops • Off-by-One errors • Spaghetti code • Use for loops for their intended purpose • Forgetting a semicolon • A semicolon too many • Don’t use != to test the end of a range

  10. Reference: Big Java 2nd Edition by Cay Horstmann 8.1.1 while Loops (section 7.1 in Big Java) 8.1.2 for Loops (section 7.2 in Big Java)

More Related