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
- C Programming Basics
- C Programming Operators
- C printf and Scanf
- While loop in C
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
- Read the base and exponent from the user.
- Initialize a variable
result
to 1. - Initialize a counter variable
i
to 0. - While
i
is less than the exponent, do steps 5-7. - Multiply
result
by the base and store the result back inresult
. - Increment the value of
i
by 1. - Repeat steps 4-6 until
i
is equal to the exponent. - 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 usingscanf()
. - The variables
result
andi
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.