Menu
Topics Index
...
`

Forward and Backward For loop


If you need explanation Read this topic

If you need Answer Take test on this topic

Forward and Backward For loop
Given the same system performance, which of the following for loops execute faster?

X: for(int i = 100000; i > 0; i--)
    {
    }
Y: for(int i = 1; i < 100001; i++)
    {
    }

A. Y executes faster than X
B. X executes faster than Y
C. Both will execute in same time
D. Can not be predicted
Topic: for 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

Posted by Ramya Reddy Addulla    2015-03-13 03:41:02


ans is (b)

Posted by Anuj Batham    2015-03-13 03:54:13


Answer is C because both X and Y loops same number of times.

Posted by Santosh Kumar    2015-03-13 11:07:13


Ans is A

Y executed faster than X.

--in Y: for loop counter is increased I.e. addition is used so it is fast.

--X uses subtraction so 2's compilation is used which takes more time.

Y executes faster than X.

Posted by Mânïshå Mùlchåndânï    2015-03-13 17:11:57


A

Posted by Induja Chinna    2015-03-14 08:18:41


ans b .. This is because in bytecode comparison with 0 is a different operation than comparison with a non-zero number. Actually i < 10001 requires to first load the number on stack then execute comparison, while i > 0 is executed as one operation. Of course there will be no speed difference in most cases because of JVM optimizations.decrement is faster compared to increment

Posted by Maheshwari Natarajan    2015-03-14 09:41:26


Answer is B.

Posted by Shashanka Mogaliraju    2015-03-15 17:43:47


This dose is now closed and the winners are Maheshwari Natarajan,  for 'First Correct Comment', Maheshwari Natarajan,  for 'Best Comment' and Shashanka Mogaliraju for the 'Popular Comment'. The 'lucky liker' is Shashanka Mogaliraju. 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    2015-03-16 01:51:25


© meritcampus 2019

All Rights Reserved.

Open In App