The For Statement

The 'for' loop is more compact than the 'while' and 'do' loops and automatically updates the loop counter at the end of each iteration. Both 'for' and 'while' loops are designed for different situations. You'll learn more about when to use each later.

9. Incrementing by a Variable


Answer:

start at 0, count upward by 1's, end at 7
for ( count = 0; count < 8; count++ )
start at 0, count upward by 2's, end at 14
for ( count = 0; count < 15; count += 2 )
start at 1, count upward by 2's, end at 15
for ( count = 1; count < 16; count += 2 )

Incrementing by a Variable

Here is a program fragment that uses an increment amount contained in a variable.


int count;
int inc;

// ... get inc from the user ...

for ( count = 0; count < 21; count = count + inc )
{
System.out.println( "count is: " + count );
}
System.out.println( "\nDone with the loop.\nCount is now" + count);




Enter increment value:   

     

(The actual code behind this example does some error checking not seen in the above.)


Question 9:

What is the smallest value of inc such that the loop body will execute only one time?
Confirm your answer by testing it with the program.