Java Reference
In-Depth Information
This for loop has no effect on the output statement. The semicolon at
the end of the for statement terminates the for loop; the action of the
for loop is thus empty. Both output statements are outside the scope of
the for loop, so the for loop has no effect on them. Note that this code
will output 11 .
5.
for (i = 1; ; i++)
System.out.print(i + " ");
System.out.println();
In this for loop, because the logical expression is omitted from the
for statement, the loop condition is always true . This is an infinite
loop.
5
EXAMPLE 5-14
In this example, a for loop reads five integers and finds their sum and average.
Consider the following programming code, in which i , newNum , sum ,and average
are int variables:
sum = 0;
for (i = 0; i < 5; i++)
{
newNum = console.nextInt();
sum = sum + newNum;
}
average = sum / 5;
System.out.println("The sum is " + sum);
System.out.println("The average is " + average);
In the preceding for loop, after getting a newNum , this value is added to the previously
calculated (partial) sum of all the numbers read before the current number. The variable
sum is initialized to 0 before the for loop. Thus, after the program gets the first number
and adds it to the value of sum ,thevariable sum holds the correct sum of the first
number.
Search WWH ::




Custom Search