19.09.2015 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

These errors often occur when you use the next-line block style. Using the end-of-line<br />

block style can avoid errors of this type.<br />

In the case of the do-while loop, the semicolon is needed <strong>to</strong> end the loop.<br />

int i = 0;<br />

do {<br />

System.out.println("i is " + i);<br />

i++;<br />

} while (i < 10);<br />

4.5 Which Loop <strong>to</strong> Use? 151<br />

Correct<br />

4.15 Can you convert a for loop <strong>to</strong> a while loop? List the advantages of using for loops.<br />

4.16 Can you always convert a while loop in<strong>to</strong> a for loop? Convert the following while<br />

loop in<strong>to</strong> a for loop.<br />

✓Point✓ Check<br />

int i = 1;<br />

int sum = 0;<br />

while (sum < 10000) {<br />

sum = sum + i;<br />

i++;<br />

}<br />

4.17 Identify and fix the errors in the following code:<br />

1 public class Test {<br />

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

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

4 sum += i;<br />

5<br />

6 if (i < j);<br />

7 System.out.println(i)<br />

8 else<br />

9 System.out.println(j);<br />

10<br />

11 while (j < 10);<br />

12 {<br />

13 j++;<br />

14 }<br />

15<br />

16 do {<br />

17 j++;<br />

18 } while (j < 10)<br />

19 }<br />

20 }<br />

4.18 What is wrong with the following programs?<br />

1 public class ShowErrors {<br />

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

3 int i;<br />

4 int j = 5;<br />

5<br />

6 if (j > 3)<br />

7 System.out.println(i + 4);<br />

8 }<br />

9 }<br />

1 public class ShowErrors {<br />

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

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

4 System.out.println(i + 4);<br />

5 }<br />

6 }<br />

(a)<br />

(b)

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

Saved successfully!

Ooh no, something went wrong!