While Loop in java
The ‘while loop’ is a second type loop. It is used we are not known how many times
the loop will execute. This is an entry-controlled loop. In a while loop if the
initial condition is true then the execution will enter into the loop.
Syntax
for the while loop
While(condition)
{
expression 1;
expression 2;
expression 3;
---------------;
---------------;
}
The while statement is a
repetition statement. It is an entry control loop and has the following syntax :
while
( condition ) {
//
statements
}
The statements within the while
block (between the opening and closing curly braces) are executed as long as
the condition is true.
If we have only one statement,
then there is no need to use the braces.
First, the condition is check. If the condition is true, then the statements are executed. Otherwise, nothing happens.
After executing the statements, the condition is checked. If it is true again, the
statement are executed and the condition is checked again and the process
continues till the condition becomes false.
Here is an example code which
prints numbers from 1 to 10.
int
i = 1;
while
(i <= 10) {
System.out.println(i);
i++;
}
The statement i = 1 initializes
with 1. The condition i <= 10 is true, so we enter the body of the loop. i
is printed and incremented to 2. Now again, the condition is checked and is
true. i is printed and incremented to 10. In this way, the while loop executes
and prints 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. Now when i is 10, i is printed and
incremented to 11. i <= 10 is false. So, control comes out of the loop.
Full Example
//To check whether a number is an
Armstrong or not
import java.io.*;
public class Armstrong
{
public static void main(String args[])throws IOException
{
InputStreamReader read =new
InputStreamReader(System.in);
BufferedReader in =new
BufferedReader(read);
int n, num, a, b, c,s; s=0;
System.out.println("Enter your
no.");
n= Integer.parseInt(in.readLine());
num=n;
while(n>0)
{
a=n/10;
b=a*10;
c=n-b;
s=s+c*c*c;
n=n/10;
}
if(num==s)
System.out.println("The number
" +num+ " is an Armstrong no.");
else
System.out.println("The number
" +num+ " is not an Armstrong no.");
}
More Java program