70 likes | 174 Views
“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.
E N D
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.)
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
Ex. of a regular “for” loop: for (intCounter = 1; intCounter <= 5; intCounter++) { System.out.println(“Hello!”) }
Ex. of a user controlled “for” loop: int intCounter; int intTimes = 10; for (intCounter = 1; intCounter <= intTimes; intCounter++) { System.out.println(“Hello!”) }
intCount <= 10 “for” loops are pretest loops Assign 1 to intCounter Increment intCounter Statements True False
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