# The For Statement

 Site: Saylor Academy Course: CS101: Introduction to Computer Science I Book: The For Statement
 Printed by: Guest user Date: Sunday, August 14, 2022, 9:05 PM

## Description

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.

## 1. The Fantastic For Statement

The for statement is a convenient way to program counting loops. It also can be used to build all three types of loops. Anything it does could also be done with the fundamental control statements you already know. But the for statement often says just what you want in a compact, easily understood format.

Chapter Topics:

• The three parts of all loops (review)
• Syntax of the for statement
• Using the for statement in counting loops
• Equivalence of for and while loops

Question 1:What are the three types of loops? This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 License.

## 2. Fundamental Loops

Answer:typedescriptioncounting loopUses a loop control variable to count upwards or downwards (usually by an integer increment.)sentinel-controlled loopLoop keeps going until a special value is encountered in the data.result-controlled loopLoop keeps going until a test determines that the desired result has been achieved.

# Fundamental Loops Each type of loop can be built using the while along with other statements. There are three things (in every type of loop) that must be done correctly:

1. The loop must be initialized.
2. A condition must be tested.
3. The loop body must change something that is tested.

Overlooking one of these aspects results in a defective loop. But usually each of these aspects is found in a different place in a program. No wonder that loops often go wrong!

The flow chart to the right shows what all loops must do. It could be for any of the three types of loops. The ellipses (. . . .) shows where the loop body does additional computation.

Question 2:Would it be convenient to have all three aspects combined into one statement?

## 3. For Statement

Answer:Yes, it certainly would.

# For Statement Java has a for statement which combines all three aspects of a loop. It looks like this:

for ( initialize ; test ; change )  loopBody ;

The initializetest , and change are expressions that (usually) perform the named action. The loopBody can be a single statement or a block statement.

Here is an example of a for statement:

for ( count = 0;   count < 10; count++ )  System.out.print( count + " " );

Remember that count++ has the same effect as count = count + 1.

The for loop does the same thing as this loop built using a while statement:

count = 0;  // initializewhile (  count < 10 )  // test{  System.out.print( count + " ");  count++ ;  // change}

The variable count in both loops is the loop control variable. (A loop control variable is an ordinary variable used to control the actions of a looping structure.)

Question 3:What is the output of both loops?

## 4. Any Kind of Loop

Answer:for ( count = 0;  count < 10; count++ )
System.out.print( count + " " );Outputs:0 1 2 3 4 5 6 7 8 9 

# Any Kind of Loop

Although the previous example is a counting loop, the for statement can be used to implement any of the three types of loops. The three parts, initializetest, and change can be as complicated as you want.

Here is a for loop with several statements in the loop body:

int count, sum;sum = 0;for ( count = 0;  count <= 5; count++ ){  sum = sum + count ;  System.out.print( count + " " );}System.out.println( "\nsum is: " + sum );

Since the loop body consists of several statements, they are enclosed in braces { and } to make a block.

Question 4:What is the output of this new loop? Pay careful attention to the test part of the loop.

## 5. Top-driven Loop

Answer:The output is:0 1 2 3 4 5
sum is 15

# Top-driven Loop

Here is the example for loop and its equivalent while loop:

for loop

while loop
int count, sum;
sum = 0;
for ( count = 0; count <= 5; count++ )
{
  sum = sum + count ;
  System.out.print( count + " " );
}
System.out.println( "sum is: " + sum );

int count, sum;
sum   = 0;
count = 0;
while ( count <= 5 )
{
  sum = sum + count ;
  System.out.print( count + " " );
  count++ ;
}
System.out.println( "sum is: " + sum );

Notice two important aspects of these loops:

1. The test is performed every time, just before execution is about to enter the loop body.
2. The change is performed at the bottom of the loop body, just before the test is re-evaluated.

Loops that work this way are called top-driven loops, and are usually mentally easier to deal with than other arrangements.

Look back at the loop flow chart loop flow chart to see this graphically.

Question 5:Where should the initialization part of a loop be located in order to make it mentally easy to deal with?

## 6. Active For Loop

Answer:Just above the test part of a loop. This is were for loops automatically put it, and where it is sensible to put it if you are implementing a loop with a while.


# Active For Loop

Here is another example. Notice that the loop body is a block statement although there is only one statement nested inside the block. This is syntactically correct.

int count;for ( count = 0; count < 7; count++ )  {  System.out.println( "count is: " + count ); }System.out.println( "Done with the loop" );

Here is a JavaScript version of this loop. Try to predict what it will output:

Question 6:Do you think that the change part of the for statement must always increment by one?

## 7. Small Change

Answer:No.

# Small Change

The change part can be complicated, if you want. It is best to keep it small and understandable. Here is almost the same loop as in the previous example, but now the control variable is incremented by two.

The expression count += 2 adds the value 2 to the variable count. (For more details on this see chapter 31.) Try to predict the output before you run the program.

The change to count is done at the bottom of the loop body. This means that the last value that count gets is the first one that fails the test count < 7. This is the value count will have just outside the loop body.

Questions like this are common on midterm and final examinations. If you rush, you are likely to get them wrong. But with careful thought they are easy enough.

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



Question 7:Read the description, and then fill in the blanks of the sequence. Then fill in the blanks of the loop that creates the same sequence.descriptionstart at 1, count upward by 2's, all values less than 10sequencecodefor ( count =  ; count  ;  )

## 8. Counting by Threes

Answer:descriptionstart at 1, count upward by 2's, all values less than 10sequence1 3 5 7 9codefor ( count= 1 ; count < 10; count+=2 )

# Counting by Threes

Here is almost the same loop as in the previous example, but now the control variable is incremented by THREE.

The expression count += 3 adds 3 to the value of count .

System.out.println( "\nDone with the loop.\nCount is now" + count);

int count;for ( count = 0; count <= 12; count += 3 )  {  System.out.println( "count is: " + count ); }

Here is a version of this loop. Try to predict the output before you run the program. (Notice that the test is now  <= ). (Also, pay careful attention to the value  count has just outside the loop.

Question 8:Now complete the for statement for each of the following sequencesstart at 0, count upward by 1's, end at 7for ( count = ; count < ; count++ )start at 0, count upward by 2's, end at 14for ( count = ; count < ; count += 2 )start at 1, count upward by 2's, end at 15for ( count = ; count < ; count += 2 )

## 9. Incrementing by a Variable

Answer:start at 0, count upward by 1's, end at 7for ( count = 0; count < 8; count++ )start at 0, count upward by 2's, end at 14for ( count = 0; count < 15; count += 2 )start at 1, count upward by 2's, end at 15for ( 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.

## 10. Counting Down

Answer:21

# Counting Down

Recall the general form of a for:

for ( initialize ; test ; change )  loopBody ;

The change can be any statement. It can, for example, decrease the control variable, as in this example:

int count;for ( count = 10; count >= 0; count--  )  {  System.out.println( "count is: " + count ); }System.out.println( "\nDone with the loop.\nCount is now" + count);

The expression count-- decrements count by one.

Question 10:Would the output of this program be any different if the expression count-- were changed to --count?

## 11. Omitting Parts of the for

Answer:No. In more complicated expressions using a postfix operator instead of a prefix operator usually makes a difference, but not here.

# Omitting Parts of the for

for loop
while loop
for ( initialize ; test ; change )
  loopBody ;
initialize;
while ( test )
{
  loopBody;
  change
}

Parts of a for can be omitted. Since the three parts of a for are the three parts of any loop, when a part is eliminated from a for it has to be done elsewhere. Recall that the  for is equivalent to a while.

You can omit the initialize part from the for loop. It now acts the same as a while loop with its initialize part omitted. Doing this is useful when initialization is complicated and you wish to do it in several statements before the loop. For example, initialization may depend on user input:

// get initial value of count from the user here
    for (    ; count < 13; count++  )
{
System.out.println( "count is: " + count );
}
System.out.println( "\nDone with the loop.\nCount is now" + count);

Enter initial value:

Question 11:Do you think that the change part of a for can be omitted (as long as it is done somewhere else)?

## 12. Omitting the change

Answer:Yes.

# Omitting the change

Syntactically you can omit the change part. This means that if the Java compiler sees:

for ( count = 0; count < 25;  )

it will not complain. It is now your responsibility to put statements that make a change somewhere into the loop body. For example:

for ( count = 0; count < 25;  ){  System.out.println("count is: " + count );  count = count + 1;}

would work fine. (Although in this case it would be far better to do the change in the for.)

Question 12:Can a for statement be used to implement a sentinel controlled loop?

## 13. Sentinel Controlled Loop

Answer:Yes. Now the test part of the for will look for the sentinel.

# Sentinel Controlled Loop

In a sentinel controlled loop the change part depends on data from the user. It is awkward to do this inside a for statement. So the change part is omitted from the for statement and put in a convenient location.

Below is an example. The program keeps asking the user for x and printing the square root of x. The program ends when the user enters a negative number.

This program would be better if a while statement were used in place of the for statement.

import java.util.Scanner;

public class EvalSqrt
{
public static void main (String[] args )
{
Scanner scan = new Scanner( System.in );
double x;

System.out.print("Enter a value for x or -1 to exit: ")  ;
x = scan.nextDouble();

for (    ; x >= 0.0 ;   )
{
System.out.println( "Square root of " + x + " is " + Math.sqrt( x ) );

System.out.print("Enter a value for x or -1 to exit: ")  ;
x =  scan.nextDouble();
}
}
}

Question 13:Do you think that the test part of a for can be omitted?

## 14. Omitting the Test

Answer:Yes. (Actually, a good answer would be "sounds dangerous", because it is.)

# Omitting the Test

When the test part of a for is omitted it is as if the value true were put in its place. So,

for ( initialize ;   ; change )  loopBody ;

is the same as:

for ( initialize ;  true  ; change )  loopBody ;

This is done for compatibility with the language C. It should not be used in newly written programs.

Several syntactic oddities were included in Java so that it would look familiar to C programmers.

Question 14:Could all three parts be omitted from a for?

## 15. End of Chapter

Answer:Yes.

# End of Chapter

The phrase for( ; ; ) is the same as while( true ). Sometimes people do this, although it is not very clear and should be avoided.

That's all for this chapter. Look at the following topics for a while. Click on a subject for more information.