19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

4.6 Nested Loops 153<br />

Note<br />

Be aware that a nested loop may take a long time <strong>to</strong> run. Consider the following loop<br />

nested in three levels:<br />

for (int i = 0; i < 10000; i++)<br />

for (int j = 0; j < 10000; j++)<br />

for (int k = 0; k < 10000; k++)<br />

Perform an action<br />

The action is performed one trillion times. If it takes 1 microsecond <strong>to</strong> perform the action,<br />

the <strong>to</strong>tal time <strong>to</strong> run the loop would be more than 277 hours. Note that 1 microsecond is<br />

one millionth (10 –6 ) of a second.<br />

4.19 How many times is the println statement executed?<br />

for (int i = 0; i < 10; i++)<br />

for (int j = 0; j < i; j++)<br />

System.out.println(i * j)<br />

✓Point✓ Check<br />

4.20 Show the output of the following programs. (Hint: Draw a table and list the variables<br />

in the columns <strong>to</strong> trace these programs.)<br />

public class Test {<br />

/** Main method */<br />

public static void main(String[] args) {<br />

for (int i = 1; i < 5; i++) {<br />

int j = 0;<br />

while (j < i) {<br />

System.out.print(j + " ");<br />

j++;<br />

}<br />

}<br />

}<br />

}<br />

(a)<br />

public class Test {<br />

/** Main method */<br />

public static void main(String[] args) {<br />

int i = 0;<br />

while (i < 5) {<br />

for (int j = i; j > 1; j——)<br />

System.out.print(j + " ");<br />

System.out.println("****");<br />

i++;<br />

}<br />

}<br />

}<br />

(b)<br />

public class Test {<br />

public static void main(String[] args) {<br />

int i = 5;<br />

while (i >= 1) {<br />

int num = 1;<br />

for (int j = 1; j

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!