Open In App

Power of a Number in C

Last Updated : 31 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

calculate power of a number in C

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




// C program for the above approach
#include <stdio.h>
  
// Naive iterative solution to
// calculate pow(x, n)
long power(int x, unsigned n)
{
    // Initialize result to 1
    long long pow = 1;
  
    // Multiply x for n times
    for (int i = 0; i < n; i++) {
        pow = pow * x;
    }
  
    return pow;
}
  
// Driver code
int main(void)
{
  
    int x = 2;
    unsigned n = 3;
  
    // Function call
    int result = power(x, n);
    printf("%d", result);
  
    return 0;
}


Output

8

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads