Open In App

Power Function in C/C++

Given two numbers base and exponent, the C++ or C pow() function finds x raised to the power of y i.e. x y. Basically in C/C++, the exponent value is calculated using the pow() function. The pow() function is used to calculate the power of a number in C/C++. It takes double as input and returns double as output.

We have to use #include <math.h> in C/C++  to use that pow() function in our C/C++ program.

Syntax of pow() Function

double pow (double x, double y);

pow() Function Parameters

This method takes only two arguments:

pow() Function Return Value

Example of pow() Function

Input: 2.0, 5.0
Output: 32.00
Explanation: pow(2.0, 5.0) executes 2.0 raised to the power 5.0, which equals 32
Input: 5.0, 2.0
Output: 25.00
Explanation: pow(5.0, 2.0) executes 5.0 raised to the power 2.0, which equals 25




// C program to illustrate
// power function
#include <math.h>
#include <stdio.h>
 
int main()
{
    double x = 6.1, y = 4.8;
 
    // Storing the answer in result.
    double result = pow(x, y);
    printf("%.2lf", result);
 
    return 0;
}




// C++ program to illustrate
// power function
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    double x = 6.1, y = 4.8;
 
    // Storing the answer in result.
    double result = pow(x, y);
 
    // printing the result upto 2
    // decimal place
    cout << fixed << setprecision(2) << result << endl;
 
    return 0;
}

Output
5882.79

Time Complexity: O(log(n))

Auxiliary Space: O(1)

Working of pow() Function with Integers

The pow() function takes ‘double’ as the argument and returns a ‘double’ value. This function does not always work for integers. One such example is pow(5, 2). When assigned to an integer, it outputs 24 on some compilers and works fine for some other compilers. But pow(5, 2) without any assignment to an integer outputs 25. 

One another way can be using the round function to assign it to some integer type.

Example 1: C/C++ Program to demonstrate the behavior of the pow() function with integers.




// C++ program to illustrate
// working with integers in
// power function
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int a, b;
 
    // Using typecasting for
    // integer result
    a = (int)(pow(5, 2) + 0.5);
    b = round(pow(5,2));
    cout << a << endl << b ;
 
    return 0;
}




// C program to illustrate
// working with integers in
// power function
#include <math.h>
#include <stdio.h>
 
int main()
{
    int a, b;
 
    // Using typecasting for
    // integer result
    a = (int)(pow(5, 2) + 1e-9);
    b = round(pow(5,2));
    printf("%d \n%d", a, b);
 
    return 0;
}

Output
25 
25

Time Complexity: O(log(n))
Auxiliary Space: O(1)


Article Tags :
C++