BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

C Program to Calculate the Power of a Number

By Chaitanya Singh | Filed Under: C Programs

In this tutorial, you will learn how to write C program to calculate power of a number. There are two ways you can calculate power of a number, using loop or using pow() function.

Example 1: Program to calculate power of a number using loop

In this example, we are using while loop and inside while loop we are decrementing the exponent (variable exp) by 1 and multiplying the number by itself. The loop keeps iterating until exp becomes zero. This way if the exponent is 4 the number gets multiplied by itself 4 times, which is what we need for calculating the power of a number.

#include <stdio.h>
int main() {
  int number, exp;
  long double result = 1.0;
  printf("Enter the number: ");
  scanf("%d", &number);
  printf("Enter exponent: ");
  scanf("%d", &exp);

  //storing the exponent value in a temporary variable
  //to perform some arithmetic operations on it.
  int temp = exp;
  //Multiplying the number by itself, until the "temp"
  //that contains "exp" value become zero.
  while (temp != 0) {
    result *= number;
    --temp;
  }
  printf("%d to the power %d is: %.0Lf", number, exp, result);
  return 0;
}

Output:
C Program to Calculate the Power of a Number

Example 2: Program to calculate power of a number using pow() function

In this example, we are calculating the power of a number using pow() function. This function belongs to the math.h header file so be sure to include this header file when using the pow() function.

#include <math.h>
#include <stdio.h>

int main() {
  int number, exp, result;
  printf("Enter the number: ");
  scanf("%d", &number);
  printf("Enter exponent: ");
  scanf("%d", &exp);

  // Calculating power using pow() function
  result = pow(number, exp);

  //displaying result
  printf("%d to the power %d is: %d", number, exp, result);
  return 0;
}

Output:
C Program to Calculate the Power of a Number

Related C Examples:

  • C Program to count number of digits in an integer
  • C Program to check whether a number is prime or not
  • C Program to add two numbers
  • C Program to print an integer entered by the user
❮ C TutorialC Programs ❯

Programs

  • C Programs
  • Java Programs
  • C++ Programs

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap