- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Write a power (pow) function using C++

The power function is used to find the power given two numbers that are the base and exponent. The result is the base raised to the power of the exponent.

An example that demonstrates this is as follows −

Base = 2 Exponent = 5 2^5 = 32 Hence, 2 raised to the power 5 is 32.

A program that demonstrates the power function in C++ is given as follows −

## Example

#include using namespace std; int main(){ int x, y, ans = 1; cout << "Enter the base value: \n"; cin >> x; cout << "Enter the exponent value: \n"; cin >> y; for(int i=0; i<y; i++) ans *= x; cout << x <<" raised to the power "<< y <<" is "<&;lt;ans; return 0; }

## Example

The output of the above program is as follows −

Enter the base value: 3 Enter the exponent value: 4 3 raised to the power 4 is 81

Now let us understand the above program.

The values of base and exponent are obtained from the user. The code snippet that shows this is as follows −

cout << "Enter the base value: \n"; cin >> x; cout << "Enter the exponent value: \n"; cin >> y;

The power is calculated using the for loop that runs till the value of the exponent. In each pass, the base value is multiplied with ans. After the completion of the for loop, the final value of power is stored in the variable ans. The code snippet that shows this is as follows −

for(int i=0; i<y; i++) ans *= x;

Finally, the value of the power is displayed. The code snippet that shows this is as follows −

cout << x <<" raised to the power "<< y <<" is "<<ans;

- Related Questions & Answers
- PHP pow() Function
- Is POW() better or POWER() in MySQL?
- pow() function in C
- pow() function in PHP
- Which one is better POW() or POWER() in MySQL?
- Write an iterative O(Log y) function for pow(x, y) in C++
- Write a program to calculate pow(x,n) in C++
- pow() function for complex number in C++
- Write a C program using time.h library function
- Write C program using isupper() function
- Super Pow in C++
- Power Function in C/C++
- Write you own Power without using multiplication(*) and division(/) operators in C Program
- Write a C program to Reverse a string without using a library function
- Pow(x, n) in Python