Header Ads

Power calculation in java without using pow function

How to calculate a power value of a given number

The logic is something--
2. Check out how much is the power to be calculated
3. multiply the given number in 1 for these many times (given in step-2) 

Say i have a number called 2  (getting in logic no-1)
i need to calculate the 2 to the power 4 value(getting 4 at logic no-2)
So output of that is 2*2*2*2=16

Let us implement that in code.

    public  void calcpow(int val,int powr) {
//this function takes two input ...the number and the power value
        int res=1;
  //res is the integer type temp variable  This is initialized to 1 to handle the condition where power=0. x to the power 0=1
        for(int i=1;i<=powr;i++) {
Powered by Blogger.