Posted By:
4 Feb, 2014 8:20 am PST

Using while loop in Java

The While Loop

 A while loop is a control structure that allows you to repeat a task a certain number of times.

Whatever can be done using the for loop can also be done using a while loop – the syntax is different.

Syntax:

The syntax of a while loop is:

while(Boolean_expression)

{

   //Statements

}

When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.

Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped.

For example:

Q1. Write a class While1.java that has a static function int reverse (int n) that returns the reverse of the positive number passed to it.

class While1{

public static void main(String[] args)

{

int rev;

rev = reverse (1234);

System.out.println(rev);

}

static int reverse (int n)

{

int i = n;

int answer=0;

while(i > 0)

{

int rem = n % 10;

answer = (answer * 10 ) + rem;

n = n / 10;

if ( n >0 )

i = i +1;

else

break;

}

return answer;

}

}

OUTPUT:

EXPLANATION:

Here, we have while( i > 0). The code statements that follow this, inside the curly braces {} are executed repeatedly, until the condition inside the while() loop evaluates to a false.

 The anatomy of the while statement is:

 Unending while loop

 Just as for ( ; ; ) is an unending for loop, so also, while ( true ) is an unending while loop. Such a loop will never end unless we use the break statement inside it for some condition.

 Another example:

public class Test {

   publicstaticvoid main(String args[]) {

      int x = 10;

      while( x < 20 ) {

         System.out.print("value of x : " + x );

         x++;

         System.out.print("\n");

      }

   }

}

OUTPUT:

 The do … while loop

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax:

The syntax of a do...while loop is:

 do

{

   //Statements

}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

Create a file DoWhile.java as shown below:

public class DoWhile {

public static void main(String [] args)

{

int counter = 0;

do

{

System.out.println(counter * counter);

counter ++;

}

while (counter < 5);

}

}

OUTPUT:

EXPLANATION:

In this loop, the statements to be executed are executed at least once – the loop condition is checked at the end of the code block. If the condition (counter < 5 ) is true, then control goes back to the start of the loop once again.

Anatomy of the do … while loop

Question 1:

What is the difference between a while and a do … while loop?

Answer:

The anatomy of the while loop is while ( condition ) { … } and that of the do … while loop is do { … } while (condition );

In the while loop the condition is evaluated initially, before any iteration through the loop. In the do … while loop, the loop iterates at least once, and then the condition gets evaluated to check for further iterations in the loop. In other words, the do … while loop has at least one execution of the code block, whereas in the while loop, there may be zero executions through the code block.

Question 2:

Give the syntax for infinite loops using for, while, and do … while respectively.

Answer:

Infinite loop using for is : for ( ; ; ) { … }

Infinite loop using while is : while ( true ) { … }

Infinite loop using do … while is : do { … } while (true );

More Examples:

Question:

A palindrome is a number that reads the same both left to right, and right to left. Examples are 12321, 13531, 34643, 232, and so on. Write a class Palindrome.java that has a static Boolean isPalindrome (int n) method that returns a true or a false depending on whether the parameter n passed to it is a palindrome or not.

SOLUTION:

public class Palindrome

{

public static void main(String [] args)

{

int p = 1220;

boolean y = isPalindrome( p );

if (y == true)

System.out.println(p + " is a palindrome");

else

System.out.println(p + " is not a palindrome");

 }

static int reverse (int n)

{

 int i = n;

int ans = 0;

while ( i > 0)

{

int rem = n%10;

ans = (ans * 10) + rem;

n = n / 10;

if ( n >0 )

i ++;

else

break;

}

return ans;

}

static boolean isPalindrome (int n)

{

 int b;

b = reverse (n);

if (b == n)

return true;

else

 return false;

}

}

OUTPUT:

Question :

Write a class Fibonacci.java that prints the first 10 numbers in the Fibonacci sequence, starting from 2 .The Fibonacci sequence is 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …

Solution:

public class Fibonacci {

public static void main (String [] args)

{

int i = 2;

int ans = 1;

int count = 0;

while (i > 0)

{

System.out.println(i);

int r;

r = i;

i = i + ans;

ans = r;

count ++;

if(count > 4)

break;

}

}

}

OUTPUT:



WHILE LOOP

Java while loop is used to execute statement(s) until a condition holds true.

Syntax:

 

while (condition) {
// Body of loop
}

1.   Initialization in the while loop is performed before the loop starts.

<![ 2.   If the condition holds true then the body of loop is executed, after execution of loop body condition is tested again and if the condition is true then body of loop is executed again and the process repeats until condition becomes false. Condition is always evaluated to true or false and if it is a constant, For example while (c) { …} where c is a constant then any non zero value of c is considered true and zero is considered false.

<![ 3.   Body of loop can contain more than one statement. For multiple statements you need to place them in a block using {} and if body of loop contain only single statement you can optionally use {}.

 

Example:

 

public class While {
public static void main(String[] args) {
int n=5;
 
while (n <=10) {
System.out.println("Value of n is " + n);
n++;
}
}
}

 

Attachment: While.java
Was it useful?  



How to write while loop in java?

We can use while loop to execute a body of statements continuously as long as the Boolean expression that controls entry into the loop continues to be true .

 

In Java,a while loop consists of the keyword while followed by a Boolean expression within parentheses followed by te body of the loop,which can be a single statement or a block of statements surrounded by curly braces.

 

Syntax:

               while (expression) {              

                    statement(s)              

              }

 

//To print a word JAVA three times

public class WhileExample{

            public static void main(String args[]){

                        int i =3;

                        while(i > 0){

                                    System.out.println("JAVA");

                                    i--;

                        }

            }

}

 

Output of the above program is:

JAVA

JAVA

JAVA



Attachment: WhileExample.java

Was it useful?  



The While Loop

 

 A while loop is a control structure that allows you to repeat a task a certain number of times.

Whatever can be done using the for loop can also be done using a while loop – the syntax is different.

Syntax:

The syntax of a while loop is:

while(Boolean_expression)

{

   //Statements

}

When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.

Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped.

 

For example:

 

Q1. Write a class While1.java that has a static function int reverse (int n) that returns the reverse of the positive number passed to it.

class While1{
public static void main(String[] args)
{
int rev;
rev = reverse (1234);
System.out.println(rev);
}
static int reverse (int n)
{
int i = n;
int answer=0;
while(i > 0)
{
int rem = n % 10;
answer = (answer * 10 ) + rem;
n = n / 10;
if ( n >0 )
i = i +1;
else
break;
}
return answer;
}
}

 

OUTPUT:

 

EXPLANATION:

Here, we have while( i > 0). The code statements that follow this, inside the curly braces {} are executed repeatedly, until the condition inside the while() loop evaluates to a false.

 The anatomy of the while statement is:

 Unending while loop

 Just as for ( ; ; ) is an unending for loop, so also, while ( true ) is an unending while loop. Such a loop will never end unless we use the break statement inside it for some condition.

 Another example:

public class Test {
   publicstaticvoid main(String args[]) {
      int x = 10;
      while( x < 20 ) {
         System.out.print("value of x : " + x );
         x++;
         System.out.print("\n");
      }
   }
}

 

OUTPUT:

 

 

The do … while loop

do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax:

The syntax of a do...while loop is:

do

{

   //Statements

}while(Boolean_expression);

 

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

Create a file DoWhile.java as shown below:

public class DoWhile {
public static void main(String [] args)
{
int counter = 0;
do
{
System.out.println(counter * counter);
counter ++;
}
while (counter < 5);
}
}

OUTPUT:

 

EXPLANATION:

In this loop, the statements to be executed are executed at least once – the loop condition is checked at the end of the code block. If the condition (counter < 5 ) is true, then control goes back to the start of the loop once again.

Anatomy of the do … while loop

 

Question 1:

What is the difference between a while and a do … while loop?

Answer:

The anatomy of the while loop is while ( condition ) { … } and that of the do … while loop is do { … } while (condition );

In the while loop the condition is evaluated initially, before any iteration through the loop. In the do … while loop, the loop iterates at least once, and then the condition gets evaluated to check for further iterations in the loop. In other words, the do … while loop has at least one execution of the code block, whereas in the while loop, there may be zero executions through the code block.

Question 2:

Give the syntax for infinite loops using for, while, and do … while respectively.

Answer:

Infinite loop using for is : for ( ; ; ) { … }

Infinite loop using while is : while ( true ) { … }

Infinite loop using do … while is : do { … } while (true );

More Examples:

Question:

A palindrome is a number that reads the same both left to right, and right to left. Examples are 12321, 13531, 34643, 232, and so on. Write a class Palindrome.java that has a static BooleanisPalindrome (int n) method that returns a true or a false depending on whether the parameter n passed to it is a palindrome or not.

SOLUTION:

public class Palindrome
{
public static void main(String [] args)
{
int p = 1220;
boolean y = isPalindrome( p );
if (y == true)
System.out.println(p + " is a palindrome");
else
System.out.println(p + " is not a palindrome");
 }
static int reverse (int n)
{
 int i = n;
int ans = 0;
while ( i > 0)
{
int rem = n%10;
ans = (ans * 10) + rem;
n = n / 10;
if ( n >0 )
i ++;
else
break;
}
return ans;
}
static boolean isPalindrome (int n)
{
 int b;
b = reverse (n);
if (b == n)
return true;
else
 return false;
}
}

OUTPUT:

 

Question :

Write a class Fibonacci.java that prints the first 10 numbers in the Fibonacci sequence, starting from 2 .The Fibonacci sequence is 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …

Solution:

public class Fibonacci {
public static void main (String [] args)
{
int i = 2;
int ans = 1;
int count = 0;
while (i > 0)
{
System.out.println(i);
int r;
r = i;
i = i + ans;
ans = r;
count ++;
if(count > 4)
break;
}
}
}

OUTPUT:


Was it useful?  




Please login to reply to this problem.



Related Problems on Fixoncloud