What is the value of ‘number’ after the following code fragment execution?

int number = 0;
int number2 = 12;
while (number < number2)
{
number = number + 1;
}

Options
- 5
- 12
- 21
- 13


CORRECT ANSWER : 12

Discussion Board
Java

int number = 0;
int number2 = 12;
while (number < number2)
{
number = number + 1;
System.out.println(number);
}
//number < number2 -> It's means, continue loop will be perform(0 to 12) & every time increment +1 if we getting value 12 then loop will be terminated.
Exp- 0=0+1=1;
0=1+1=2;
0=2+1=3;
0=2+1=4;
.............
...........
0=11+1=12
then loop will be terminated.
o/p- 12.

Brij Prasad 09-22-2016 07:29 AM

answer

It will give compile time error, because of there is no semicolon in front of 12

mallinath 04-19-2015 11:47 AM

while loop

The while statement continually executes a block of statements while a particular condition is true. The syntax is as follows:

while (expression) {
statement(s)
}

while statement returns a boolean values whenever it evaluates the expression. If the expression is true then the statement(s) are executed, otherwise the expression evaluates to false.

So, as per the above definition if you see the program in execution the program will run till the number is less than 12 and that is till 11<12. The moment it has become the condition will become false and it will execute out of the loop. So, the answer would be 12.

Rohit Sharma 07-29-2014 01:49 AM

Answer :

Because it's a while loop,
it rounds 0 to 11 times.
that is number = 12

M. Tuhin 05-6-2014 03:37 AM

Hi

For the above question, can you please explain in detail, on what basis value of variable "number" will be "12"

Siddu 02-8-2014 04:51 PM

value of variable "number" after execution of code fragment

For the above question, can you please explain in detail, on what basis value of variable "number" will be "12"

Soujanya D 12-13-2013 10:09 AM

Write your comments


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)


Advertisement