// (from the Carter book)
// Exercise 4.5 - Question 2 (a & b):
// Describe what the fragment does and then re-write it using
// a WHILE statement.
import java.awt.*;
import hsa.Console;
public class Exercise45B_Chapter4
{
static Console c; // The output console
public static void main (String[] args)
{
c = new Console ();
// Question 2 (a):
// 1) in a FOR loop, 'i' must be declared and initialized to 0.
// 2) in a FOR loop, 'i' is compared to 10 (i < 10).
// 3) in a FOR loop, 'i' is incremented by 1.
// 4) in the body of the FOR loop, x = 2 * i - 10 is calculated.
// 5) in the body of the FOR loop, y = Math.abs (x / 5 - 2) is
// calculated.
// 6) in the body of the FOR loop, both 'x' and 'y' are printed out.
// NOTE: 'x' and 'y' should also be declared as type int, but are not.
// Re-written as a WHILE loop:
int i = 0, x, y;
while (i < 10)
{
x = 2 * i - 10;
y = Math.abs (x / 5 - 2);
c.println (x + " " + y);
i++;
}
// Question 2 (b):
// 1) 'product' must be declared and initialized to 1.
// 2) in a DO loop, there is a prompt to the user to enter
// the next value (an integer called 'next').
// 3) 'next' is a value that is input by the user.
// 4) in an IF statement, 'next' is compared to 'TERMINATOR'
// (next != TERMINATOR).
// 5) in a calculation --> product *= next is performed.
// 6) in the WHILE condition at the bottom of the DO loop,
// the condition (next != TERMINATOR) must be true to stay
// in the DO loop.
// NOTE: 'product' should be displayed before the user is
// prompted for another integer value.
// Re-written as a WHILE loop:
int product = 1, next;
final int TERMINATOR = -1;
c.println ("Enter the first integer (-1 to exit): ");
next = c.readInt ();
while (next != TERMINATOR)
{
product *= next;
c.println ("product of 'i' is: " + product);
c.println ("Next value please (-1 to exit): ");
next = c.readInt ();
}
} // main method
} // Exercise45B_Chapter4 class
No comments:
Post a Comment