Docsity

Loops in Programming: while, do-while, and for, Slides of Java Programming

Partial preview of the text

Download Loops in Programming: while, do-while, and for and more Slides Java Programming in PDF only on Docsity!

Loops

Announcements

Error in HW2, problem 4b Free points for everyone May want to start HW2 early (Covers week 3, Ch 1.2-1.4) (Already 10+ days old)

Highlights

  • While (and do-while) loop
  • For loop

Loop

Often we want to do a (similar) command more than once Computer programmers call this code a loop Loops are quite powerful and are very commonly used

while loop

The boolean expression is tested when first entering the while loop And! When the end of the loop code is reached (the } to close the loop)

while loop

3 parts to any (good) loop:

  • Test variable initialized
  • boolean expression
  • Test variable updated inside loop (See: ImprovedGuessingGame.java)

do-while loop

Q: Why would I ever want a do-while loop? A: When the first time the variable is set is inside the loop. You can initialize the variable correctly and use a normal while loop, but this makes the logic harder (Kitty code) (See: Password.java)

for loop

A for loop is a compacted version of the while loop (the 3 important parts are together) for loops are used normally when iterating over a sequence of numbers (i.e. 1, 2, 3, 4) (See: ForLoop.java) Initialization boolean expression Update

for loop

Very often used for String parsing (See: StringToNumber.java) If time... (See: StringToNumberSneaky.java)