Calculate Power Of A Number Without Using Pow Method

C Program To Calculate Power Of A Number Without Using Pow Method Using While Loop

In this tutorial, you will learn how to write a program to calculate power of a number without using pow method using while loop conditional statement.

Required Knowledge

Problem Statement

Write a program to calculate the power of a number without using the pow() method. The program should take two inputs: the base number and the exponent. It should then calculate and display the result of raising the base number to the power of the exponent.

Example

Input:
Base: 3
Exponent: 4

Output:
3 raised to the power of 4 is 81

Algorithm

  1. Read the base and exponent from the user.
  2. Initialize a variable result to 1.
  3. Initialize a counter variable i to 0.
  4. While i is less than the exponent, do steps 5-7.
  5. Multiply result by the base and store the result back in result.
  6. Increment the value of i by 1.
  7. Repeat steps 4-6 until i is equal to the exponent.
  8. Print the value of result as the final result.

Program to calculate power of a number without using pow method

#include <stdio.h>
int main() {
    int base, exponent;
    printf("Enter the base number: ");
    scanf("%d", &base);
    printf("Enter the exponent: ");
    scanf("%d", &exponent);
    int result = 1;
    int i = 0;
    while (i < exponent) {
        result *= base;
        i++;
    }
    printf("%d raised to the power of %d is %d\n", base, exponent, result);
    return 0;
}

Output

Enter the base number: 3
Enter the exponent: 4
3 raised to the power of 4 is 81

Program Explanation

  • The program prompts the user to enter the base number and exponent using printf() and reads the input values using scanf().
  • The variables result and i are initialized to 1 and 0, respectively.
  • The while loop is used to calculate the power of the number.
  • Inside the loop, the result variable is updated by multiplying it with the base.
  • The i variable is incremented by 1 in each iteration.
  • The loop continues until i becomes equal to the exponent.
  • Finally, the program prints the result using printf().

Conclusion

This program calculates the power of a number without using the pow() method by using a while loop to repeatedly multiply the base with itself. By incrementing the counter variable until it reaches the exponent, the loop effectively calculates the desired power. The result is then displayed to the user.