224k views
1 vote
The counter variable in the code below increments by 1 each time through the loop. What will the value of counter be after the following loop executes?

var counter = 0;
var n = 6;
while(n > 0){
n = n - 2;
counter = counter + 1;
}
console.log(counter)
4

A. 0
B. 1
C. 2
D. 3
E. 4

User Sherman Lo
by
6.3k points

1 Answer

6 votes

Answer:

The Value of the variable counter will be 3

Step-by-step explanation:

The code snipped given in the question will execute only three times.

The value of counter will be increased by 1 afer each execution with the initial value of counter set to 0

The condition while n>0 will hold true at the first iteration when n=6. (counter will be increased to 1) and n is reduced by 2 (new value of n =4).

The condition while n>0 will hold true at the second iteration when n=4-2 =2. (counter will be increased to 2) and n is reduced by 2 (new value of n =2).

The condition while n>0 will hold true at the third iteration when n=2-2. (counter will be increased to 3) and n is reduced by 2 (new value of n =0).

At the fourth iteration, the condition becomes false as the value of n is now zero and 0 is not greater than 0. So the the condition becomes false with the value of counter = 3

User Krm
by
6.3k points