In this program, you’ll learn to calculate the power of a number with and without using pow() function.
Example 1: Calculate power of a number using a for loop
C++ Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> using namespace std; int main() { system ("CLS"); //to clear the screen int base,exponent,res; cout<<"Enter value of base: "; cin>>base; cout<<"Enter value of exponent: "; cin>>exponent; long result = 1; while (exponent != 0) { result *= base; --exponent; } cout<<"Result="<<result; return 0; } |
Example 2: Calculate power of a number using a pow() Function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include<iostream> #include<math.h> //for pow() function using namespace std; int main() { system ("CLS"); //to clear the screen int base,exponent,result; cout<<"Enter value of base: "; cin>>base; cout<<"Enter value of exponent: "; cin>>exponent; result=pow(base,exponent); cout<<"Result="<<result; return 0; } |
Output: