w3resource

C++ Exercises: Calculate x raised to the power n


5. Calculate x Raised to the Power n

Write a C++ program to calculate x raised to the power n (xn).

Sample Input: x = 7.0
n = 2
Sample Output: 49

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

// Function to calculate x^n
double powxn(double x, int n) {
    // If the exponent is negative, change x to 1/x and make n positive
    if (n < 0) {
        x = 1 / x;
        n = -n;
    }

    double result = 1; // Initialize the result

    // Loop to multiply x 'n' times to calculate the power
    for (auto i = 0; i < n; ++i) {
        result = result * x;
    }

    return result; // Return the final result
}

int main(void) {
    // Test cases for calculating x^n and displaying results
    double x = 7.0;
    int n = 2;
    cout << "\n" << x << "^" << n << " = " << powxn(x, n) << endl; 

    x = 3;
    n = 9;
    cout << "\n" << x << "^" << n << " = " << powxn(x, n) << endl; 

    x = 6.2;
    n = 3;
    cout << "\n" << x << "^" << n << " = " << powxn(x, n) << endl;         

    return 0; // Return 0 to indicate successful completion
}

Sample Output:

7^2 = 49

3^9 = 19683

6.2^3 = 238.328

Flowchart:

Flowchart: Calculate x raised to the power n.

For more Practice: Solve these Related Problems:

  • Write a C++ program to calculate x^n using recursion with a divide and conquer approach (exponentiation by squaring).
  • Write a C++ program that computes the power of a number iteratively and compares the result with a recursive method.
  • Write a C++ program to implement a function that calculates x raised to n using a loop and handles negative exponents by inverting the result.
  • Write a C++ program that uses recursion to compute x^n and prints the intermediate values of x at each recursive call.

C++ Code Editor:



Contribute your code and comments through Disqus.

Previous: Write a C++ program to divide two integers (dividend and divisor) without using multiplication, division and mod operator.
Next: Write a C++ program to get the fraction part from two given integers representing the numerator and denominator in string format.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.