C

Calculate The Power Of A Number In C

This tutorial will teach you how to write a C program to calculate the power of a number. You can calculate the power of a number in two ways: with a loop or with the pow() function.

Example 1: A program that uses a loop to calculate the power of a number.

In this example, we use a while loop, and within it, we decrement the exponent (variable exp) by one and multiply the number by itself. The loop iterates until exp equals zero. If the exponent is 4, the number is multiplied by itself four times, which is what we need to calculate a number’s power.

#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;
}

Example 2: Use the pow() function to calculate the power of a number.

In this example, we use the pow() function to calculate the power of a number. This function is part of the math.h header file, so make sure to include it 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;
}

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button