Power of a Number Program in C++

Advertisements

Sum of Digits in C++ Convert Decimal to Binary in C++

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. To understand this code you need good knowledge of For Loop in C++

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 

Sum of Digits in C++ Convert Decimal to Binary in C++

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements