
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- pow() function in C
- Write an iterative O(Log y) function for pow(x, y) in C++
- PHP pow() Function
- pow() function for complex number in C++
- pow() function in PHP
- Write a program to calculate pow(x,n) in C++
- Is POW() better or POWER() in MySQL?
- Which one is better POW() or POWER() in MySQL?
- Write a C program using time.h library function
- Write C program using isupper() function
- Power Function in C/C++
- Super Pow in C++
- Write a C program to Reverse a string without using a library function
- Write a C program to compare two strings using strncmp library function
- Write you own Power without using multiplication(*) and division(/) operators in C Program
