The While Loop
It is a repetitive control structure, and executes the statements with the body until the condition becomes false.
Syntax:
while(condition)
{
. . . . . .
body of the loop; // statements
. . . . . .
}
Example:
while(n>0)
{
i=n+i;
n++
}
System.out.println(“I Value is : “ + i);
The statements within the while loop will be executed till the condition is true, when the condition becomes false the control passes to the first statement that follow the body of the while loop.
Example: 1
Program to print sum of digits
public class whileDemo
{
public static void main(String args[])
{
int n=258;
int n1, sum=0;
while(n>0)
{
n1=n%10;
sum=sum+n1;
n=n/10;
}
System.out.println(“The Result is : “ + sum);
getch();
}
Output will be
The Result is : 15
Example: 2
public class whileDemo1
{
public static void main(String args[])
{
int n=6;
System.out.println(“Initial Value of n is: “+n);
while(n>1)
{
System.out.println(“Inside while loop”);
System.out.println(“Now the N value is : “+n);
--n;
}
System.out.println(“The out of the While loop! “);
}
}
Output will be
Initial Value of n is: 6
Inside while loop
Now the N value is :6
Inside while loop
Now the N value is :5
Inside while loop
Now the N value is :4
Inside while loop
Now the N value is :3
Inside while loop
Now the N value is :2
The out of the While loop!
Note : Example: 1 file name should be whileDemo.java and Example: 1 file name should be whileDemo1.java
No comments:
Post a Comment