English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of C Programming Examples
In this example, you will learn to calculate the power of a number.
To understand this example, you should understand the followingC programmingTopic:
The following program takes two integers (a base and an exponent) from the user and calculates the power.
For example, in2 3in the case of
2is the base
3is the exponent
is equivalent to 2*2*2
#include <stdio.h> int main() { int base, exp; long long result = 1; printf("Enter base: "); scanf("%d", &base); printf("Enter exponent: "); scanf("%d", &exp); while (exp != 0) { result *= base; --exp; } printf("Power = %lld", result); return 0; }
Output Result
Enter base: 3 Enter exponent: 4 Power = 81
This technique is only valid when the exponent is a positive integer.
If you need to find the power of any real number, you can use the pow() function.
#include <math.h> #include <stdio.h> int main() { double base, exp, result; printf("Enter base: "); scanf("%lf", &base); printf("Enter exponent: "); scanf("%lf", &exp); //Calculate Power Value result = pow(base, exp); printf("%.0lf",1lf^%.0lf1lf = %.0lf2lf", base, exp, result); return 0; }
Output Result
Enter base: 2.3 Enter exponent: 4.5 2.3^4.5 = 42.44