Java Reference
In-Depth Information
4.11 Explain what happens when a Java program attempts to divide one integer by another.
What happens to the fractional part of the calculation? How can you avoid that outcome?
4.12 Describe the two ways in which control statements can be combined.
4.13 What type of repetition would be appropriate for calculating the sum of the first 100 posi-
tive integers? What type would be appropriate for calculating the sum of an arbitrary number of pos-
itive integers? Briefly describe how each of these tasks could be performed.
4.14 What is the difference between preincrementing and postincrementing a variable?
4.15 Identify and correct the errors in each of the following pieces of code. [ Note: There may be
more than one error in each piece of code.]
a) if (age >= 65 );
System.out.println( "Age is greater than or equal to 65" );
else
System.out.println( "Age is less than 65 )";
b) int x = 1 , total;
while (x <= 10 )
{
total += x;
++x;
}
c) while (x <= 100 )
total += x;
++x;
d) while (y > 0 )
{
System.out.println(y);
++y;
4.16
What does the following program print?
1
// Exercise 4.16: Mystery.java
2
public class Mystery
3
{
4
public static void main(String[] args)
5
{
6
int x = 1 ;
7
int total = 0 ;
8
9
while (x <= 10 )
10
{
11
int y = x * x;
12
System.out.println(y);
13
total += y;
14
++x;
15
}
16
17
System.out.printf( "Total is %d%n" , total);
18
}
19
} // end class Mystery
For Exercise 4.17 through Exercise 4.20, perform each of the following steps:
a)
Read the problem statement.
b)
Formulate the algorithm using pseudocode and top-down, stepwise refinement.
c)
Write a Java program.
Search WWH ::




Custom Search