Iteration Statements
Java’s iteration statements are for, while and do-while. These statements create what we commonly call loops. A loop repeatedly executes the same set of instructions until a termination condition is met. As you will see Java has a loop to fit any programming need.
While Loop
The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its controlling expression is true. Here is its general form:
while(condition)
{
// body of loop
}
The condition can be any Boolean expression.
The body of the loop will be executed as long as the conditional expression is true.
When condition becomes false, control passes to the next line of code immediately following the loop.
The curly braces are unnecessary if only a single statement is being repeated.
// Demonstrate the while loop.
class WLWhile
{
public static void main(String args[])
{
int n = 5;
while(n > 0)
{
System.out.println("tick " + n);
n--;
}
}
}
Type following command in command prompt
javac WLWhile.java
java WLWhile
tick 5
tick 4
tick 3
tick 2
tick 1
No comments:
Post a Comment
If you have any query please comment here, Will get back to you :)