Java Reference
In-Depth Information
4.3
x = x + 1 ;
x += 1;
++x;
x++;
4.4
a) z = x++ + y;
b) if (count > 10 )
System.out.println( "Count is greater than 10" );
c) total -= --x;
d) q %= divisor;
q = q % divisor;
4.5
a) int sum = 0 ;
b) int x = 1 ;
c) sum += x; or sum = sum + x;
d) System.out.printf( "The sum is: %d%n" , sum);
4.6
The program is as follows:
1
// Exercise 4.6: Calculate.java
2
// Calculate the sum of the integers from 1 to 10
3
public class Calculate
4
{
5
public static void main(String[] args)
6
{
7
int sum = 0 ;
8
int x = 1 ;
9
10
while (x <= 10 ) // while x is less than or equal to 10
11
{
12
sum += x; // add x to sum
13
++x; // increment x
14
}
1 16
System.out.printf( "The sum is: %d%n" , sum);
17
}
18
} // end class Calculate
The sum is: 55
4.7 product = 25 , x = 6
4.8 a) Error: The closing right brace of the while statement's body is missing.
Correction: Add a closing right brace after the statement ++c; .
b) Error: The semicolon after else results in a logic error. The second output statement
will always be executed.
Correction: Remove the semicolon after else .
4.9 The value of the variable z is never changed in the while statement. Therefore, if the loop-
continuation condition (z >= 0 ) is true, an infinite loop is created. To prevent an infinite loop from
occurring, z must be decremented so that it eventually becomes less than 0.
Exercises
4.10 Compare and contrast the if single-selection statement and the while repetition statement.
How are these two statements similar? How are they different?
Search WWH ::




Custom Search