Thursday, 18 December 2014

// The "Exercise41B_Chapter4" class.
// (from the Carter book)

// Question 4 of Exercise 4.1:

// Using a WHILE loop, determine which integer input value is less than
// or equal to 2 to the power of 'n'.  For example, if the input number
// is 25, then 32 = 2 to the power of 5, which is when the for loop stops.
// (NOTE: 'x' is the base and 'y' is the power in this exercise.)

import java.awt.*;
import hsa.Console;

public class Exercise41B_Chapter4
{
    static Console c;           // The output console

    public static void main (String[] args)
    {
        c = new Console ();

        c.println ("Please enter a positive integer (>= 0)");
        int number = c.readInt ();

        int y = 0;            // this is the power variable (increases by 1)
        int x = (int) Math.pow (2, y); // exponents are always double values

        while (number > x)
        {
            y++;
            x = (int) Math.pow (2, y);
            c.println ("x: " + x);

        }
        c.print (x + " or " + "2 ^ " + y
                + " is greater than or equal to "
                + number + ".");


    } // main method
} // Exercise41B_Chapter4 class

No comments:

Post a Comment