Write a method called printNumbers that accepts a maximum number as an argument
ID: 3669518 • Letter: W
Question
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 printPowersOf 2 that acccpts a maximum number as an argument and prints each power ol 2 from 2 degree (1) up to that maximum power, inclusive. For example, consider the following calls: PrintPowersOf2(3); PrintPowersOf2(10); These calls should produce the following output: 12 4 8 1 2 4 8 16 32 64 128 256 512 1024Explanation / Answer
1.
import java.io.*;
import java.util.*;
class Numbers
{
public static void main( String args[])
{
int n,i;
Scanner s = new Scanner( System.in);
System.out.println(" Enter Numbers to Display : ");
n=s.nextInt();
for( i=0; i<=n; i++)
{
System.out.println( " The Number Series is [ "+i "]");
}
}
}
Output:
Enter Numbers to Display : 7
The Number Series is [ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] [ 7 ]
2.
/*This program displays the powers of 2
* which are less than or equal to 2^n
* where n is a given input number
*/
public class PowerOfTwo
{
public static void main(String[] args)
{
int n, i=0;
System.out.println(" Enter the value of n : ");
Scanner s = new Scanner( System.in);
n = s.nextInt();
int power =1;
System.out.println("Powers of 2 that are less than 2^"+n);
while (i <= n)
{
System.out.println("2^"+i+" = " + power);
power = power *2;
i++;
}
}
}
Output:
Enter the value of n : 4
Powers 2 that are less than 2^4
2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
/*This program displays the powers of 2
* which are less than or equal to 2^n
* where n is a given input number
*/
public class PowerOfTwo
{
public static void main(String[] args)
{
int n, i=0;
System.out.println(" Enter the value of n : ");
Scanner s = new Scanner( System.in);
n = s.nextInt();
int power =1;
System.out.println("Powers of 2 that are less than 2^"+n);
while (i <= n)
{
System.out.println("2^"+i+" = " + power);
power = power *2;
i++;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.