Another of Java’s loops is the while.The general form of the while loop is
while (condition) statement;
where statement may be a single statement or a block of statements, and condition defines the condition that controls the loop, and it may be any valid Boolean expression. The loop repeats while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop. Here is a simple example in which a while is used to print the alphabet:
// Demonstrate the while loop.
class WhileDemo
{
public static void main(String args[])
{
char ch;
// print the alphabet using a while loop
ch = 'a';
while(ch <= 'z')
{
System.out.print(ch); ch++;
}
}
}
Here,chis initialized to the letter a. Each time through the loop,chis output and then incremented. This process continues until ch is greater than z. As with the for loop, the while checks the conditional expression at the top of the loop, which means that the loop code may not execute at all. This eliminates the need for performing a separate test before the loop. The following program illustrates this characteristic of the while loop. It computes the integer powers of 2, from 0 to 9.
// Compute integer powers of 2.
class Power
{
public static void main(String args[])
{
int e; int result;
for(int i=0; i < 10; i++)
{
result = 1;
e = i;
while(e > 0)
{
result *= 2; e--;
}
System.out.println("2 to the " + i + " power is " + result);
}
}
}
The output from the program is shown here:
2 to the 0 power is 1
2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
2 to the 4 power is 16
2 to the 5 power is 32
2 to the 6 power is 64
2 to the 7 power is 128
2 to the 8 power is 256
2 to the 9 power is 512
0 comments:
Post a Comment