
- 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 program to calculate pow(x,n) in C++
In this problem, we are given two integers x and n. Our task is to write a program to calculate the pow(x,n).
Let’s take an example to understand the problem,
Input
x = 5 , n = 3
Output
125
Program to calculate the pow(x,n),
Example
#include <iostream> using namespace std; float myPow(float x, int y) { if(y == 0) return 1; float temp = myPow(x, y / 2); if (y % 2 == 0) return temp*temp; else { if(y > 0) return x*temp*temp; else return (temp*temp)/x; } } int main() { float x = 5; int n = 7; cout<<x<<" raised to the power "<<n<<" is "<<myPow(x, n); return 0; }
Output
5 raised to the power 7 is 78125
The program shows an efficient approach by dividing the power into half and then multipling the two half and also considers the negative cases.
- Related Articles
- Pow(x, n) in Python
- Write a power (pow) function using C++
- Write an iterative O(Log y) function for pow(x, y) in C++
- Write a C# program to calculate a factorial using recursion
- Write C program to calculate balance instalment
- Write a program to Calculate Size of a tree - Recursion in C++
- Python Program to calculate n+nm+nmm.......+n(m times).
- Write a Golang program to calculate the sum of elements in a given array
- Calculate n + nn + nnn + … + n(m times) in Python program
- Program to find sum of 1 + x/2! + x^2/3! +…+x^n/(n+1)! in C++
- C++ Program to calculate the value of sin(x) and cos(x)
- Calculate n + nn + nnn + u + n(m times) in Python Program
- Write a program to calculate the least common multiple of two numbers JavaScript
- pow() function in C
- pow() function in PHP

Advertisements