100 likes | 112 Views
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.
E N D
Week 8 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham
Week 8 Topics 8.1.1 while Loops 8.1.2 for Loops
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.
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; }
8.1.1 while Loops cont. False balance < targetBalance ? True Increment years Add interest to balance
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);
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.1.2 for Loops cont. i = 1 initialization False condition i <= years? True Add interest to balance update i++
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
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)