C Program to calculate the power of a number

In this example, we take one user input and calculate power of number using different methods

C Program to Calculate the Power of a Number Using Loop

	
#include <stdio.h>
int main()
{
    int i = 1, no, Exponent; 
    long power = 1;
    
    printf("\n Please Enter any no : ");
    scanf(" %d", &no);

    printf("\n Please Enter the Exponent Vlaue: ");
    scanf(" %d", &Exponent);
    
    while(i <= Exponent)
    {
        power = power * no;
        i++;
    }
    printf("\n The Final result of %d power %d = %ld", no, Exponent, power);
    
    return 0;
}
	

Output :

	
Please Enter any no : 5
Please Enter the Exponent Vlaue: 2
The Final result of 5 power 2 = 25
	

C Program to Reverse Inputted Number Using User Define Function

	
#include <stdio.h>
double pow(double no, int Exponent);
int main()
{
    int no, Exponent;
    double power;
    
    printf("\n Please Enter any no : ");
    scanf(" %d", &no);
    printf("\n Please Enter the Exponent Vlaue: ");
    scanf(" %d", &Exponent);
    power = pow(no, Exponent); 
    printf("\n The Final result of %d power %d = %.2lf", no, Exponent, power);
    
    return 0;
}
double pow(double no, int Exponent)
{
    if(Exponent == 0)
        return 1;
    else if(Exponent > 0)
        return no * pow(no, Exponent - 1);
    else
        return 1 / pow(no, -Exponent);
}
	

Output :

	
Please Enter any no : 3
Please Enter the Exponent Vlaue: 5
The Final result of 3 power 5 = 243.00
	

C Program to Reverse Inputted Number Using pow() Function

	
#include &t;stdio.h>
#include &t;math.h>
int main()
{
  int i = 1, no, Exponent; 
  long power = 1;
  
  printf("\n Please Enter any no : ");
  scanf(" %d", &no);

  printf("\n Please Enter the Exponent Vlaue: ");
  scanf(" %d", &Exponent);

  printf("\n The Final result of %d power %d = %.2lf", no, Exponent, pow(no, Exponent));
  
  return 0;
}
	

Output :

	
Please Enter any no : 5
Please Enter the Exponent Vlaue: 4
The Final result of 5 power 4 = 625.00
	

The above program can only calculate powers when the exponent is positive. To calculate the power of a number for any real exponent use the pow() function.

To use the pow() function make sure to include math.h header file at the top of the program.


Share your thoughts

Ask anything about this examples