Java Reference
In-Depth Information
LISTING 6.2
continued
OUTPUT
Enter a positive integer: 2896
That number reversed is 6982
The do loop in the ReverseNumber program uses the remainder operation to
determine the digit in the 1's position, then adds it into the reversed number, then
truncates that digit from the original number using integer division. The do loop
terminates when we run out of digits to process, which corresponds to the point
when the variable number reaches the value zero. Carefully trace the logic of this
program with a few examples to see how it works.
If you know you want to perform the body of a loop at least once, then you
probably want to use a do statement. A do loop has many of the same properties
as a while statement, so it must also be checked for termination conditions to
avoid infinite loops.
SELF-REVIEW QUESTIONS (see answers in Appendix N)
SR 6.8
Compare and contrast a while loop and a do loop.
SR 6.9
What output is produced by the following code fragment?
int low = 0, high = 10;
do
{
System.out.println (low);
low++;
} while (low < high);
SR 6.10 What output is produced by the following code fragment?
int low = 10, high = 0;
do
{
System.out.println (low);
low++;
} while (low <= high);
SR 6.11 Write a do loop to obtain a sequence of positive integers from the
user, using zero as a sentinel value. The program should output the
sum of the numbers.
 
Search WWH ::




Custom Search