Difference between revisions of "Print Powers of Two"
Line 28: | Line 28: | ||
An image or By Students section | An image or By Students section | ||
− | |Solution= | + | |Solution= |
+ | First, you will need to declare 2 variables, one for the exponent and one for the answer. | ||
+ | <pre> | ||
+ | int exp; | ||
+ | int ans; | ||
+ | </pre> | ||
<pre> | <pre> | ||
+ | for (int i=0; i<10; i++) | ||
+ | { | ||
+ | ans=1; | ||
+ | exp=i; | ||
+ | |||
+ | while(exp>0) | ||
+ | { | ||
+ | ans *= 2; | ||
+ | exp --; | ||
+ | } | ||
+ | |||
+ | System.out.println("2 to the power of " + i + " is " + ans); | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </pre> | ||
+ | |SolutionCode=<pre> | ||
class PowersOfTwo | class PowersOfTwo | ||
{ | { | ||
Line 54: | Line 76: | ||
} | } | ||
</pre> | </pre> | ||
− | |||
}} | }} |
Revision as of 10:45, 6 April 2010
Back to the Program-A-Day homepage
ProblemRemember that a while loop will execute infinitely until a specified condition is met. A for loop is similar except that the number of iterations is specified as an argument for the loop. Using both for and while loops, create a program that prints the powers of 2 from <math>2^0</math> <math>2^9</math>.
2 to the power of 0 is 1 2 to the power of 1 is 2 2 to the power of 2 is 4 2 to the power of 3 is 8 2 to the power of 4 is 16 2 to the power of 5 is 32 2 to the power of 6 is 64 2 to the power of 7 is 128 2 to the power of 8 is 256 2 to the power of 9 is 512
|
SideSectionTitle
An image or By Students section | |
---|---|---|
SolutionFirst, you will need to declare 2 variables, one for the exponent and one for the answer. int exp; int ans; for (int i=0; i<10; i++) { ans=1; exp=i; while(exp>0) { ans *= 2; exp --; } System.out.println("2 to the power of " + i + " is " + ans); } } } | ||
Code |