1 / 7

“for” loops

“for” loops. Two categories of loops: Conditional Loops: Execute as long as a certain condition exists. Count-Controlled Loops: Must initialize a control variable to a starting value. Must test the control variable against a max value. When max value is reached the loop terminates.

Download Presentation

“for” loops

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. “for” loops

  2. Two categories of loops: • Conditional Loops: • Execute as long as a certain condition exists. • Count-Controlled Loops: • Must initialize a control variable to a starting value. • Must test the control variable against a max value. When max value is reached the loop terminates. • The loop must update the control variable each iteration. (The control variable is the same thing as a Counter.)

  3. The “for” loop is ideal for writing count-controlled loops. It initializes, tests, and updates the control variable (counter). • Syntax: for (Initialization; Test; Update) { Statements; } Loop Header

  4. Ex. of a regular “for” loop: for (intCounter = 1; intCounter <= 5; intCounter++) { System.out.println(“Hello!”) }

  5. Ex. of a user controlled “for” loop: int intCounter; int intTimes = 10; for (intCounter = 1; intCounter <= intTimes; intCounter++) { System.out.println(“Hello!”) }

  6. intCount <= 10 “for” loops are pretest loops Assign 1 to intCounter Increment intCounter Statements True False

  7. Formatting output: • Use the tab command “\t” when formatting output in the command prompt. • Ex: intNumber = 7; System.out.println(intNumber + “\t” + intNumber + “\t\t” + intNumber ); Output: 7 7 7

More Related