C Language Example - Calculate the nth Power of a Number

C Language Examples

Calculate the n-th power of a number, for example: 23, where 2 is the base and 3 is the exponent.

Example - Using while

#include <stdio.h> int main() { int base, exponent; long long result = 1; printf("Base:"); scanf("%d", &base); printf("Exponent:"); scanf("%d", &exponent); while (exponent != 0) { result *= base; --exponent; } printf("Result: %lld", result); return 0; }

Run result:

基数: 2
指数: 3
结果:8

Example - Using the pow() Function

#include <stdio.h> #include <math.h> int main() { double base, exponent, result; printf("Base:"); scanf("%lf", &base); printf("Exponent:"); scanf("%lf", &exponent); // Calculate the result result = pow(base, exponent); printf("%.1lf^%.1lf = %.2lf", base, exponent, result); return 0; }

Run result:

基数: 2
指数: 3
2.0^3.0 = 8.00

Example - Recursion

#include <stdio.h> int power(int n1, int n2); int main() { int base, powerRaised, result; printf("Base:"); scanf("%d",&base); printf("Exponent (positive integer):"); scanf("%d",&powerRaised); result = power(base, powerRaised); printf("%d^%d = %d", base, powerRaised, result); return 0; } int power(int base, int powerRaised) { if (powerRaised != 0) return (base*power(base, powerRaised-1)); else return 1; }

C Language Examples

other extensions