SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Introduction To Parameters And Objects
Exercise:
Exercises
Question:3 | ISBN:9780136091813 | Edition: 2

Question

Write a method called printPowersOfN that accepts a base and an exponent as arguments and prints each power of the base from base0 (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.)

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program using Math class:

public class Ch03Ex03
{
	public static void main(String[] args)
	{
		printPowersOfN(4, 3);
		printPowersOfN(5, 6);
		printPowersOfN(-2, 8);
	}

	public static void printPowersOfN(int base, int maximum)
	{
		for (int i = 0; i <= maximum; i++)
		{
			System.out.print((int) Math.pow(base, i) + " ");
		}
		System.out.println();
	}
}

Program without using Math class:

public class Ch03Ex03
{
	public static void main(String[] args)
	{
		printPowersOfN(4, 3);
		printPowersOfN(5, 6);
		printPowersOfN(-2, 8);
	}

	public static void printPowersOfN(int base, int maximum)
	{
		int result = 1;
		System.out.print(result + " ");

		for (int i = 1; i <= maximum; i++)
		{
			result *= base;
			System.out.print(result + " ");
		}

		System.out.println();
	}
}

Output:

1 4 16 64 
1 5 25 125 625 3125 15625 
1 -2 4 -8 16 -32 64 -128 256 

 

0 0

Discussions

Post the discussion to improve the above solution.