Power of a Number in C
Last Updated :
31 Jul, 2023
In this article, we will learn how to write a C program to calculate the power of a number (xn). We may assume that x and n are small and overflow doesn’t happen.
C Program To Calculate the Power of a Number
A simple solution to calculate the power would be to multiply x exactly n times. We can do that by using a simple for or while loop.
C
#include <stdio.h>
long power( int x, unsigned n)
{
long long pow = 1;
for ( int i = 0; i < n; i++) {
pow = pow * x;
}
return pow ;
}
int main( void )
{
int x = 2;
unsigned n = 3;
int result = power(x, n);
printf ( "%d" , result);
return 0;
}
|
Complexity Analysis
- Time Complexity: O(n), to iterate n times.
- Auxiliary Space: O(1)
Please visit the article Write the Program to Find pow(x,y) to know about more methods to calculate the power of a number.
Related Articles
Share your thoughts in the comments
Please Login to comment...