QuesAns Print Page – CSKC
Sign In

Search

siteicon
Q&A ICSE2014-03H #7414

Question:

Study the method and answer the given questions.

public void sampleMethod()
{ for( int i=0; i<3; i++ )
{ for( int j=0; j<2; j++)
{ int number = (int)(Math.random() * 10);
System.out.println(number); } } }

(i) How many times does the loop execute?
(ii) What is the range of possible values stored in the variable number?

Answer:

(i) The outer loop executes 3 times ( i= 0, 1, 2) and for each execution of the outer loop, the inner loop executes two times ( j= 0, 1).
So, the inner loop executes 3 * 2 = 6 times
(ii) Math.random() returns a value between 0 (inclusive) and 1 (exclusive).
Math.random() * 10 will be in the range 0 (inclusive) and 10 (exclusive)
(int)(Math.random() * 10) will be in the range 0 (inclusive) and 9 (inclusive) (only integer values)