Reputation: 3
I want to create a piece of code with Math.pow
For instance, if I put as a ground number 2 and power level 6
I want the result to count from 0 to 6.
2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
2^5 = 32
2^6 = 64
This is what I currently have: (on JSFiddle)
function callPow(){
var val= document.getElementById("txt").value;
var power= document.getElementById("txt2").value;
alert(Math.pow(val,power));
}
Upvotes: 0
Views: 750
Reputation: 31
Alternately you may also do it using a while
loop
function callPow(){
var val= document.getElementById("txt").value;
var power= document.getElementById("txt2").value;
var count=0;//as you want to start from power 0
while ( count<= power){
alert(val + "^"+ count++ +"="+Math.pow(val,count));
}
}
Fiddle for this will be http://jsfiddle.net/g4maC/7/
Upvotes: 3
Reputation: 63
A simple for
loop should suffice.
Something like this
function callPow(){
var val= document.getElementById("txt").value;
var power= document.getElementById("txt2").value;
for(count=0; count<= power; count++){
alert(val + "^"+ count+"="+Math.pow(val,count));
}
}
Also here's the updated fiddle
Upvotes: 3
Reputation: 5309
Here is the code
<script>
function callPow(){
var val= document.getElementById("txt").value;
var power= document.getElementById("txt2").value;
for(var i=0; i<=power; i++)
{
alert(Math.pow(val,i));
}
}
</script>
Input number :<input type="text" id="txt" value=""/>
to the power<input type="text" id="txt2" value=""/>
<button onclick="callPow();">Show Value</button>
Upvotes: 0
Reputation: 36794
All you need is a loop that will count up to your specified power and alert each time:
function callPow(){
var val= document.getElementById("txt").value;
var power= document.getElementById("txt2").value;
for(i=0; i<= power; i++){
alert(val+' ^ '+i+' = '+Math.pow(val,i));
}
}
Upvotes: 4