Power of a Number Program in C++


Prev Tutorial Next Tutorial

Find Power of any Number in C++

For Calculate Power of any number, multiply particular number by itself on the basis of power. Suppose you want to calculate 2^3 is 2*2*2=8.

For calculating the power of any number user have four possibilities to input values.

  • Value of power is +ve
  • Value of Power is -ve
  • Value of Base is +ve
  • Value of Base is -ve
  • Value of power is 0

Find Power of any Number

This code only work for when we input +ve power, +ve base value, -ve base value. But it's not work when we enter -ve power value.

Example

#include<iostream.h>
#include<conio.h>

 void main()
  {
   int b,p,i,pow=1;
   clrscr();
   cout<<"Enter base and power: ";
   cin>>b>>p;
   for(i=p;i>0;i--)
   {
   pow=pow*b;
   }
   cout<<"power is: "<<pow;

  getch();
  }

Output

Enter base and power: 2  3
Power is : 8  

Find Power of any Number

This code satisfy all above Five conditions.

Example

#include<iostream.h>
#include<conio.h>

 void main()
  {
   float b,p,i,pow=1;
   clrscr();
   cout<<"Enter base and power: ";
   cin>>b>>p;
   if(p>0)
   {
   for(i=p;i>0;i--)
   {
   pow=pow*b;
   }
   }
   else if(p<0)
   {
    p=p * -1;
    for(i=p;i>0;i--)
    {
    pow=pow*b;
    }
    pow=1/pow;
   }
   else if(p==0)
   {
   pow=1;
   }
   cout<<"power is: "<<pow;

  getch();
  }

Output

Enter base and power: 2  -2
Power is : 0.25  

Find Power of a Number Using Recurtion

Example

#include<iostream.h>
#include<conio.h>

void main()
  {
   int pow(int,int);
   int a,b,r;
   clrscr();
   cout<<"Enter base and power: ";
   cin>>a>>b;
   r=pow(a,b);
   cout<<"pow: "<<r;
   getch();
   }
   int pow(int x,int y)
   {
   if(y==0)
   return(1);
   else
   {
   return(x*pow(x,y-1));
   }
  }

Output

Enter base and power: 3  3
Pow = 27 

Prev Tutorial Next Tutorial

Google Advertisements
Download Projects

Google Adsense Advertisements

Buy 3 Year Old Domain, Tutorialday.com, SeosmoTools.com @$200

Buy This Ad Space @$50 per Month, Ad Size 300X250 Contact on: hitesh.xc@gmail.com WhatsApp no. 8882538826

Yahoo Advertisements