info@meritcampus.com    +91-85006-22255
...
`

Print numbers in reverse order using while91
What will be the output of the following program?
`class WhileExample{    public static void main(String s[])    {        int n = 5;        while( n > 0 )        {            n--;            System.out.println("n = " + 5 );        }    }}`

 A. n = 4n = 3n = 2n = 1 B. n = 4n = 3n = 2n = 1n = 0 C. n = 5n = 4n = 3n = 2n = 1n = 0 D. n = 5n = 5n = 5n = 5n = 5
Topic:

### User comments below.All of them might not be correct.

Answer is d......n = 5 will be printed 5 times because anything enclosed inside " " will be printed as it is and in our case constant output will be printed in every iteration ....condition n>0 is satisfied five times and when n= 0 , control will come out of while loop

Posted by Shashanka Mogaliraju    2014-12-02 09:29:41

ans is D  as n is initialized with 5 and in the pretest while(n>0) is satisfied as n=5  n   is decremented by 1 and prints n=5 as  in the S.o.p("n="+5) is given and in the same way n value n=5 is printed until n becomes  n<0

Posted by Ramya Reddy Addulla    2014-12-02 09:35:51

Here we have the concept of while loop. It repeats the statement or a block while its controlling expression is true. Syntax of while is shown below:

while ( expression )
{
Statement;
}

The expression must return a boolean value, if the expression is true, then the while loop executes the statement in the while block until the controlling expression become false.

In the given program, n is initialized to 5. In the while it checks the condition n>0 i.e., 5>0 since the condition is true, it enters the block. Anything given in the s.o.p its printsas it is. It is given as +5  so the n value will be printed as 5. Now the n value decrements and checks for the condition again and prints again 5 due to s.o.p. it continues decrement the value by 1 and prints n = 5 until the condition become false. Finally when it comes to 0 condition become false and comes out the loop. Finally n = 5 can be printed 5 times.

Posted by Sai Ram    2014-12-02 14:08:43

This dose is now closed and the winners are Shashanka Mogaliraju,  for 'First Correct Comment', Sai Ram,  for 'Best Comment' and Sai Ram for the 'Popular Comment'. The 'lucky liker' is Varun Kumar. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2014-12-03 01:32:58