Java Reference
In-Depth Information
Exercises
1. Write a method called printNumbers that accepts a maximum number as an argument and prints each number
from 1 up to that maximum, inclusive, boxed by square brackets. For example, consider the following calls:
printNumbers(15);
printNumbers(5);
These calls should produce the following output:
[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15]
[1] [2] [3] [4] [5]
You may assume that the value passed to printNumbers is 1 or greater.
2. Write a method called printPowersOf2 that accepts a maximum number as an argument and prints each power of
2 from 2 0 (1) up to that maximum power, inclusive. For example, consider the following calls:
printPowersOf2(3);
printPowersOf2(10);
These calls should produce the following output:
1 2 4 8
1 2 4 8 16 32 64 128 256 512 1024
You may assume that the value passed to printPowersOf2 is 0 or greater. (The Math class may help you with this
problem. If you use it, you may need to cast its results from double to int so that you don't see a .0 after each
number in your output. Also try to write this program without using the Math class.)
3. Write a method called printPowersOfN that accepts a base and an exponent as arguments and prints each power of
the base from base 0 (1) up to that maximum power, inclusive. For example, consider the following calls:
printPowersOfN(4, 3);
printPowersOfN(5, 6);
printPowersOfN(-2, 8);
These calls should produce the following output:
1 4 16 64
1 5 25 125 625 3125 15625
1 -2 4 -8 16 32 64 -128 256
You may assume that the exponent passed to printPowersOfN has a value of 0 or greater. (The Math class may help
you with this problem. If you use it, you may need to cast its results from double to int so that you don't see a .0 after
each number in your output. Also try to write this program without using the Math class.)
4. Write a method called printSquare that accepts a minimum and maximum integer and prints a square of lines of
increasing numbers. The first line should start with the minimum, and each line that follows should start with the
next-higher number. The sequence of numbers on a line wraps back to the minimum after it hits the maximum. For
example, the call
printSquare(3, 7);
Search WWH ::




Custom Search