Exercise:
Write a C Program to calculate the power of a number.
1. Calculate using While loop
Click Here to View the Solution!
#include <stdio.h>
int main() {
int base, exp;
long long result = 1;
printf("Enter a base number: ");
scanf("%d", &base);
printf("Enter an exponent: ");
scanf("%d", &exp);
while (exp != 0) {
result *= base;
--exp;
}
printf("Result= %lld", result);
return 0;
}
Click Here to View the Output!
Enter a base number: 2
Enter an exponent: 5
Result= 32
Click Here to View the Explanation!
- This program is used to calculate the power of number by using a
while loop
. - Two integer variables
base
andexp
are initialized along with along long
type variableresult
asresult = 1
. - The program requests the user to enter a base value and an exponent value and stores them in the variables
base
andexp
using thescanf()
functions. - A
while loop
is initialized with the conditionexp != 0
which states that the iteration will continue until the value of exponent will become 0. - In every iteration, the base is multiplied with result and stored in
result
itself and each time the value of exponent is decremented by one. - After the while condition becomes false, the result is printed.
- The
return 0 statement
is used to exit the program execution.
2. Calculate using pow() function
Click Here to View the Solution!
#include <math.h>
#include <stdio.h>
int main() {
double base, exp, result;
printf("Enter a base number: ");
scanf("%lf", &base);
printf("Enter an exponent: ");
scanf("%lf", &exp);
result = pow(base, exp);
printf("%.1lf^%.1lf = %.2lf", base, exp, result);
return 0;
}
Click Here to View the Output!
Enter a base number: 3
Enter an exponent: 6
3.0^6.0 = 729.00
Click Here to View the Explanation!
- This program is used to calculate the power of number by using the
pow() function
. - The double type variables
base
,exp
andresult
are initialized. - The program requests the user to enter a base value and an exponent value and stores them in the variables
base
andexp
using thescanf()
functions. - The power is calculated by using the
base
andexp
as the parameters of thepow() function
and store the output in the variable result. - The result is printed and displayed on the screen.
- The
return 0 statement
is used to exit the program execution. - The
pow() function
can calculate the power with a real number as an exponent.