Search

Friday, December 14, 2018

The for Loop

You have been using a simple form of the for loop since Module 1. You might be surprised at just how powerful and flexible the for loop is. Let’s begin by reviewing the basics, starting with the most traditional forms of the for. The general form of the for loop for repeating a single statement is
for (initialization;condition;iteration)statement;
 For repeating a block,
the general form is
for(initialization;condition;iteration)
{
statement sequence
}
 The initialization is usually an assignment statement that sets the initial value of the loop control variable,which acts as the counter that controls the loop. The condition is a Boolean expression that determines whether or not the loop will repeat. The iteration expression defines the amount by which the loop control variable will change each time the loop is repeated. Notice that these three major sections of the loop must be separated by semicolons. The for loop will continue to execute as long as the condition tests true. Once the condition becomes false, the loop will exit, and program execution will resume on the statement following the for. The following program uses a for loop to print the square roots of the numbers between 1 and 99. It also displays the rounding error present for each square root.

// Show square roots of 1 to 99 and the rounding error. 
class SqrRoot 
{
 public static void main(String args[]) 

double num, sroot, rerr;
for(num = 1.0; num < 100.0; num++) 
{
 sroot = Math.sqrt(num); 
System.out.println("Square root of " + num + " is " + sroot);
// compute rounding error 
rerr = num - (sroot * sroot);
 System.out.println("Rounding error is " + rerr);
 System.out.println();
}
}
}
Notice that the rounding error is computed by squaring the square root of each number. This result is then subtracted from the original number, thus yielding the rounding error. The for loop can proceed in a positive or negative fashion, and it can change the loop control variable by any amount. For example, the following program prints the numbers 
100 to –95,
 in decrements of 5.

// A negatively running for loop. 
class DecrFor 
{
 public static void main(String args[]) 
{
 int x;
for(x = 100; x > -100; x -= 5) 
System.out.println(x);
}
}
An important point about for loops is that the conditional expression is always tested at the top of the loop. This means that the code inside the loop may not be executed at all if the condition is false to begin with.
 Here is an example:

for(count=10; count < 5; count++) x += count; 
// this statement will not execute


This loop will never execute because its control variable,count, is greater than 5 when the loop is first entered. This makes the conditional expression,count < 5, false from the outset; thus, not even one iteration of the loop will occur.



0 comments:

Post a Comment