Menu
Topics Index
...
`

Print numbers in reverse order using dowhile


If you need explanation Read this topic

If you need Answer Take test on this topic

Print numbers in reverse order using dowhile
What will be output of the following program?
class DoWhile
{
    public static void main(String s[])
    {
        int n = 5;

        do
        {
            System.out.println("n = " + n);
            n--;
        } while ( n < 2 );

    }
}

A. n = 5
n = 4
n = 3
n = 2
n = 1
B. n = 5
n = 4
n = 3
C. n = 5
D. Compilation errors
Topic: do while Loop In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

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

c.... do whilebis a exit control loop i.e it controls on the exit condition....in do while operation is performed first den condition is chek.... here frstly n=5 ..it entrrs into do loop prints n and decrement its value... after den it cheks the while condition... as n>2 condition fails and it exits the loop.... and only 5 is printed

Posted by Asma Mujtaba Khan    2014-12-05 08:43:40


ans is c  The concept is exit and entry loop
do while is exit
while is entry
for is one king of such loop
peculiar thing is that do while stops executing statements if the condition is false
It also stops when the condtion reaches zero // sound diiferent

Posted by Sai Veerendra    2014-12-05 08:55:06


c

Posted by Himani Mittal    2014-12-05 09:30:22


Answer is C..

Here we have the concept of do while loop. Do while loop is similar to while loop. But do while loop executes all the statements in the block at least once and checks the condition at the end. If the condition is true then it re executed all the statements. It continue to check the condition and executes the statements until the condition become false. The syntax of do while loop as shown below :

do
{
// body of statement
}
while(condition);

Note : we should always terminate do while loop using semicolon (;)

Coming to the given program, here 'n' is initialized to 5. Now the control enters the do block and prints n=5. Then the 'n' value is decremented by 1, so n becomes 4 now and checks for the condition 4<2 which is false. So it leads to terminate the loop. Finally the output is n = 5.

Note : removing semicolon ( ; ) leads to compilation error.

Posted by Sai Ram    2014-12-05 19:51:27


This dose is now closed and the winners are Sai Ram,  for 'First Correct Comment', Sai Ram,  for 'Best Comment' and Asma Mujtaba Khan for the 'Popular Comment'. The 'lucky liker' is Sai Ram. 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-06 02:55:03


© meritcampus 2019

All Rights Reserved.

Open In App