Find power of any number


Prev Tutorial Next Tutorial

Program to find power of any number

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.

program power of a number

#include<stdio.h>
#include<conio.h>

 void main()
  {
   int b,p,i,pow=1;
   clrscr();
   printf("Enter base and power: ");
   scanf("%d%d",&b,&p);
   for(i=p;i>0;i--)
   {
   pow=pow*b;
   }
   printf("power is: %d",pow);

  getch();
  }

Output

Enter base and power: 2  3
Power is : 8  

Find power of any number

This code satisfy all above Five conditions.

Program to find power of any number

#include<stdio.h>
#include<conio.h>

 void main()
  {
   float b,p,i,pow=1;
   clrscr();
   printf("Enter base and power: ");
   scanf("%f%f",&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;
   }
   printf("power is: %f",pow);

  getch();
  }

Output

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

Find power of any number using recursion

Program to find power of any number

#include<stdio.h>
#include<conio.h>

void main()
  {
   int pow(int,int);
   int a,b,r;
   clrscr();
   printf("Enter base and power  ");
   scanf("%d%d",&a,&b);
   r=pow(a,b);
   printf("power is: %d ",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
Power is: 27 

Prev Tutorial Next Tutorial

Advertisements




Facebook Likes

Advertisements