Search

Friday, December 14, 2018

Loops with No Body

In Java, the body associated with a for loop (or any other loop) can be empty. This is because a null statement is syntactically valid. Body-less loops are often useful.
 For example, the following program uses one to sum the numbers 1 through 5.

// The body of a loop can be empty.
 class Empty3 

public static void main(String args[])
 {
 int i; 
int sum = 0;
// sum the numbers through 5 
for(i = 1; i <= 5; sum += i++) ;
System.out.println("Sum is " + sum);
}
}
The output from the program is shown here:
Sum is 15
Notice that the summation process is handled entirely within the for statement, and no body is needed. Pay special attention to the iteration expression:
sum += i++

Don’t be intimidated by statements like this. They are common in professionally written Java programs and are easy to understand if you break them down into their parts. In words, this statement says “add to sum the value of sum plus i, then increment i.” Thus, it is the same as this sequence of statements:
sum = sum + i; i++;


0 comments:

Post a Comment