निम्नलिखित में से कौन सा कोड सबसे अधिक कुशल है?
Which of the following code is most efficient ?
Code 1;
for(var number=10;number>=1;number--)
{
document.writeln(number);
}
Code 2 ;
var number=10;
while(number>=1)
{
document.writeln(number);
number++;
}
A
Code 1
B
Code 2
C
Both Code 1 and Code 2
D
Cannot Compare
Explanation
Here’s a concise explanation:
Code 1:
- It uses a
forloop that correctly counts down from 10 to 1, and stops after 10 iterations.
Code 2:
- It uses a
whileloop but increments the number, which causes an infinite loop because the conditionnumber >= 1never becomes false.
Result:
- Code 1 is efficient because it works as expected.
- Code 2 creates an infinite loop, making it inefficient.
Correct Answer: (A) Code 1.
Correct Answer: A) Code 1