C++ Program to Find Power of a Number using For loop
ADVERTISEMENTS
C++ program to find power of a number using for loop. In this article, you will learn how to find power of a number in c++ language using for loop.
Syntax to calculate the power of N number
x ^ y = results
C++ Program to Find Power of a Number using For loop
// C++ Program to Find Power of a Number using For loop
#include <iostream>
using namespace std;
int main() {
int b, x, i;
long long r = 1;
// b - Value of the base number
// x - Value of the exponent number
// r - Value of the result value
cout << "-----Enter the input of base number-----\n";
cin >> b;
cout << "\n-----Enter the input of exponent number-----\n";
cin >> x;
for (i = x; i > 0; i--) {
r *= b;
}
cout << "\nThe calculation of the power of N number is " << b << "^" << x << " = " << r << "\n";
return 0;
}
Output
-----Enter the input of base number-----
5
-----Enter the input of exponent number-----
4
The calculation of the power of N number is 5^4 = 625
C++ Program to Find Power of a Number using pow() Function
Note: you have to load cmath header file to call the pow() function.
// C++ Program to Find Power of a Number using pow() Function
#include <iostream>
#include <cmath>
using namespace std;
// cmath header file loaded to call the pow() function
int main() {
double b, x, r;
// b - Value of the base number
// x - Value of the exponent number
// r - Value of the result value
cout << "-----Enter the input of base number-----\n";
cin >> b;
cout << "\n-----Enter the input of exponent number-----\n";
cin >> x;
r = (double) pow(b, x);
cout << "\nThe calculation of the power of N number is " << b << "^" << x << " = " << r << "\n";
return 0;
}
Output
-----Enter the input of base number-----
6.4
-----Enter the input of exponent number-----
3.5
The calculation of the power of N number is 6.4^3.5 = 663.178